【发布时间】:2020-10-03 21:08:41
【问题描述】:
这与我之前的 question 有关识别每个 id 的数据帧中的值的出现有关。这次我试图识别每个 id 长度为 4 或更多的连续测量值。
例如
下面是长度为4的w连续出现的例子
id t1 t2 t3 t4 t5 t6
1 s s w w w w
对于相同的 id,长度为 4 的 w 连续出现以及最后一个 w 之后出现 4 次非 w 的示例
id t3 t4 t5 t6 t7 t8 t9 t10
1 w w w w r s s s
我想将其保存在 df 中:
id t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
1 s s w w r s s s
我的数据集有和没有连续出现 w 的格式:
id t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
1 s s w w w w r s s s #after t2 value there are 4 occ. of w and after t6 (last one) there are 4 non-w occ.
2 s w w w e w w s t v #no 4 consecutive w occurrence and no 4 non-w occurrence after t7
3 w w w w w d s s s r #5 occ. of w after t5
4 e w w w w w w w w w #9 occ. of w after t1
5 w e w w w w r r r r #4 occ. of w after t2 and 4 occ. of non-w after t6
6 w s w r w r w w s w #no 4 consecutive w occurance
输出:
id t1 t2 t3 t4 t5 t6 t7 t8 t9 t10
1 s s w w r s s s
3 w d s s s r
4 e w
5 w r r r r
如何将此格式拆分为 2 个 df,一个带有开始值,一个带有结束值?
例如
df1:
id t1 t2 t3
1 s s w
以及 id2、id3 的其他起始案例...
df2:
id t6 t7 t8 t9 t10
1 w r s s s
以及 id2、id3 的其他终端情况...
样本数据:
df<-structure(list(id=c(1,2,3,4,5,6), t1=c("s","s","w","e","w","w"), t2=c("s","w","w","w","e","s"),t3 = c("w","w","w","w","w","w"),
t4 = c("w","w","w","w","w","r"), t5 = c("w","e","w","w","w","w"), t6 = c("w","w","d","w","w","r"),
t7= c("r","w","s","w","r","w"), t8 = c("s","s","s","w","r","w"), t9=c("s","t","s","w","r","s"), t10=c("s","v","r","w","r","w")), row.names = c(NA, 6L), class = "data.frame")
根据 w 标识起点和终点的代码:
Start(不工作连续时间步):
df1 <- df
df1[-1] <- t(apply(df[-1], 1, function(x) replace(x, seq_along(x) > match('w', x), '')))
df1<-df1[rowSums(df1 == 'w')!=0, ,drop = FALSE]
End(连续时间步不工作):
df2 <- df
df2[-1] <- t(apply(df[-1], 1, function(x) replace(x, seq_along(x) <= match('w', x), '')))
df2 <- df2[c(TRUE, colSums(df2[-2] != '') > 0)]
df2<-df2[rowSums(df2 == 'w')!=0, ,drop = FALSE]
【问题讨论】:
-
第 5 行以 w,e,w 开头,但您的输出会下降,为什么?
-
这个问题的第二部分是要求不能作为数据框的内容,因为每个 ID 中的列数不太可能相同。
-
...而且,为什么在问题的开头引用“4 个连续”而在末尾引用“6”?
-
@r2evans 感谢您抽出宝贵时间。原因是 t1 处的 w 不是 4 个或更多连续序列的一部分。因此,在 t1 和 t2 的 w 之后,有一个非 w 值。
-
@r2evans 是的,抱歉更新了