您可以使用which
和diff
帮助确定发生下降趋势的位置,并使用它cumsum
来填写组成员资格.
# set up new column with all 0s df$downward.trend.seq <- 0 # use diff to identify indices to change to 1 df$downward.trend.seq[which(c(NA, diff(df$measurement)) > 0)] <- 1 # use cumsum to fill in proper group membership df$downward.trend.seq <- cumsum(df$downward.trend.seq)