繁体   English   中英

如何列出由R中的循环生成的数据帧?

[英]How do I make a list of data frames generated by loops in R?

如何列出循环生成的数据帧?

这是我的循环:

> 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

任何帮助深表感谢! 谢谢

你可以做

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

暂无
暂无

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

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