我有一个数据集,该数据集的每一列均包含不同的度量值,最后一列则包含值(0,1,2)。
例如,假设我的数据框看起来像这样(忽略v1:v5的值)
1. v1 v2 v3 v4 v5 v6
2. 24 76 98 89 87 2
3. 24 76 98 89 87 2
4. 24 76 98 89 87 1
5. 24 76 98 89 87 2
6. 24 76 98 89 87 2
我对v6列的值感兴趣,我想提取值等于2的行。在上面的示例中,我想提取前2行并将其保存为新的数据帧,还提取第5行和第六行作为其他数据框并保存。更清楚地说,当我的值等于2并且是结果时,我需要将它们另存为新数据框。当值不同时,我需要循环忽略它,然后再次找到感兴趣的值(为2)。如果我的数据帧在最后一列中有70个结果块2,则我需要以70个数据帧结束。
我尝试了循环,但是我对R和编程还是相当陌生,我被困住了。
这是我到目前为止尝试过的:
>
>
>
>x=1
>for (i in 1:nrow(dataframe)) {
>
> if (dataframe[i,lastcolumn] == 2 && x==1) {
>
> start.event <- dataframe[i,]
>
> }
>
> if (dataframe[i,lastcolumn] != 2) {
> end.event <- dataframe[i-1,]
>
> }
>
> else {
>
> df[1] <- dataframe( start.event:end.event , )
> x = 1
> }
> }
我真的很感谢您的帮助。
提前致谢
一种方法是grp
根据v6
更改时间创建组()。筛选出所有行v6 != 2
并拆分grp
new_d <- subset(transform(df, grp = cumsum(c(1, diff(v6) != 0))), v6 == 2)
split(new_d, new_d$grp)
#$`1`
# v1 v2 v3 v4 v5 v6 grp
#1 24 76 98 89 87 2 1
#2 24 76 98 89 87 2 1
#$`3`
# v1 v2 v3 v4 v5 v6 grp
#4 24 76 98 89 87 2 3
#5 24 76 98 89 87 2 3
或者通过dplyr
,
library(dplyr)
new_d <- df %>%
mutate(grp = cumsum(c(1, diff(v6) != 0))) %>%
filter(v6 == 2)
split(new_d, new_d$grp)
使用的数据
structure(list(v1 = c(24L, 24L, 24L, 24L, 24L), v2 = c(76L, 76L,
76L, 76L, 76L), v3 = c(98L, 98L, 98L, 98L, 98L), v4 = c(89L,
89L, 89L, 89L, 89L), v5 = c(87L, 87L, 87L, 87L, 87L), v6 = c(2L,
2L, 1L, 2L, 2L)), .Names = c("v1", "v2", "v3", "v4", "v5", "v6"
), class = "data.frame", row.names = c(NA, -5L))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句