繁体   English   中英

如何在R中使用for循环来对我的数据进行一些更改?

[英]How I can use for loop in R to make some change in my data?

如果有人可以帮助我,我将非常感激:

我有这样的数据集:

1   0
2   0
3   0
4   1
1   0
2   0
3   0
4   1
1   0
2   0
3   0
4   1
1   0
2   0
3   0
4   1
1   0
2   0
3   0
4   1
1   0
2   1
3   0
4   0

有没有什么方法可以用于循环和打印,使我的数据像这样?

1   0
2   0
3   0
4   1
[*,*,1]: 1    2  :=
1   0
2   0
3   0
4   1
[*,*,2]: 1    2  :=
1   0
2   0
3   0
4   1
[*,*,3]: 1    2  :=
1   0
2   0
3   0
4   1
[*,*,4]: 1    2  :=
1   0
2   0
3   0
4   1
[*,*,5]: 1    2  :=
1   0
2   1
3   0
4   0

我用手做了200行,现在我真的无法继续这样做!

我们可以使用基于创建的分组进行split方法是将值为1的第一列的累积和加入到data.frames list

lst1 <- split(df1, cumsum(df1$col1 == 1))

现在,我们可以遍历listprint的顺序

 for(i in seq_along(lst1)) { 
    cat(paste0("[*,*,", i, "]: 1  2 :="), "\n")
    cat(do.call(paste, c(lst1[[i]], sep="\t", collapse="\n")), sep="\n")
    }
#[*,*,1]: 1  2 := 
#1  0
#2  0
#3  0
#4  1
#[*,*,2]: 1  2 := 
#1  0
#2  0
#3  0
#4  1
#[*,*,3]: 1  2 := 
#1  0
#2  0
#3  0
#4  1
#[*,*,4]: 1  2 := 
#1  0
#2  0
#3  0
#4  1
#[*,*,5]: 1  2 := 
#1  0
#2  0
#3  0
#4  1
#[*,*,6]: 1  2 := 
#1  0
#2  1
#3  0
#4  0

数据

df1 <- structure(list(col1 = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), col2 = c(0L, 
0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 
0L, 0L, 1L, 0L, 1L, 0L, 0L)), class = "data.frame", row.names = c(NA, 
-24L))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM