r - 如何制作由 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
推荐阅读
- typescript - 如何将数组方法与联合类型元素一起使用?
- python - 如何使用 Youtube Data APIv3 获取多个视频的统计信息?
- ios - AR Kit 2.0 跟踪来自服务器的图像
- php - FFMPEG 没有“解码”正确的 url 输入
- python - Keras 时间序列输入形状
- c++ - 调用默认构造函数时模板可变参数编译错误
- html - Bootstrap 4.1.3,下拉菜单不起作用
- macos - 如何在 Mac 上安装 Homebrew?dyld:库未加载:@rpath/libssl.1.0.0.dylib
- qt - Cmake 在 QTCreator 中没有正确解析
- common-lisp - 如何获取函数的参数数量