如何列出由循环生成的数据帧?
这是我的循环:
> for (i in 1:3) {
+ x <- c(1:3)
+ y <- c(1:3)
+ df1 <- data.frame("col1"=i*3, "col2"=y+i*3)
+ print(df1)
+ }
col1 col2
1 3 4
2 3 5
3 3 6
col1 col2
1 6 7
2 6 8
3 6 9
col1 col2
1 9 10
2 9 11
3 9 12
但是当我运行df1时,会发生这种情况:
> print(df1)
col1 col2
1 9 10
2 9 11
3 9 12
这就是我想要看到的:
print(df1)
col1 col2
1 3 4
2 3 5
3 3 6
col1 col2
1 6 7
2 6 8
3 6 9
col1 col2
1 9 10
2 9 11
3 9 12
非常感谢您的帮助!谢谢
答案 0 :(得分:4)
你可以
x <- c(1:3) # no need for y because its the same as x
out <- vector("list", length(x)) # pre-allocate space for the three data.frames
for (i in x) {
# fill the list with the data.frames
out[[i]] <- data.frame("col1" = i*3, "col2" = x + i*3)
}
结果
out
#[[1]]
# col1 col2
#1 3 4
#2 3 5
#3 3 6
#[[2]]
# col1 col2
#1 6 7
#2 6 8
#3 6 9
#[[3]]
# col1 col2
#1 9 10
#2 9 11
#3 9 12