Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在循环中更改多个数据帧_R_For Loop_Dataframe - Fatal编程技术网

R 在循环中更改多个数据帧

R 在循环中更改多个数据帧,r,for-loop,dataframe,R,For Loop,Dataframe,例如,我有三个数据集(在我的例子中,它们更多,并且有很多变量): data\u frame1您可以将数据帧放入列表中,然后使用lappy逐个处理它们。所以在这种情况下不需要使用循环 例如,您可以执行以下操作: data_frame1 <- data.frame(a=c(1,5,3,3,2), b=c(3,6,1,5,5), c=c(4,4,1,9,2)) data_frame2 <- data.frame(a=c(6,0,9,1,2), b=c(2,7,2,2,1), c=c(8,4

例如,我有三个数据集(在我的例子中,它们更多,并且有很多变量):


data\u frame1您可以将数据帧放入列表中,然后使用
lappy
逐个处理它们。所以在这种情况下不需要使用循环

例如,您可以执行以下操作:

data_frame1 <- data.frame(a=c(1,5,3,3,2), b=c(3,6,1,5,5), c=c(4,4,1,9,2))
data_frame2 <- data.frame(a=c(6,0,9,1,2), b=c(2,7,2,2,1), c=c(8,4,1,9,2))
data_frame3 <- data.frame(a=c(0,0,1,5,1), b=c(4,1,9,2,3), c=c(2,9,7,1,1))

ll <- list(data_frame1,data_frame2,data_frame3)
lapply(ll,function(df){
  df$log_a <- log(df$a)          ## new column with the log a
  df$tans_col <- df$a+df$b+df$c  ## new column with sums of some columns or any other           
                                 ##   transformation
  ###  .....
  df

})

我也有同样的需求,并希望更改我的实际数据帧列表中的列

我发现了一个很好的方法(问题中的
purr::map2
方法适用于不同列的数据帧),然后是

list2env(list_of_dataframes ,.GlobalEnv)

谢谢你能给我解释一下另一种方法吗?我已经看过你删除的评论了。你说有一种不太复杂的方法可以做到这一点。不,一些列的日志,其他列的其他转换…@agstudy我在我的数据上尝试了你的解决方案。我注意到它并没有真正编写新的变量。在您的示例中,log_a和tans_col不会插入到数据帧中。当然我搞错了…。@this.is.not.a.nick在这种情况下,我使用
$
将创建新变量。。df$log\u a将创建一个名为log\u a的变量…您对数据做了哪些尝试?@agstudy是的,但是如果按照您的示例,我然后键入
ll[[1]]$log\u a
,R将返回我
NULL
@this.is.not.a.nick这很正常,R在ll的副本中进行转换,因此您需要像我想象的那样执行
ll,我的问题很愚蠢非常感谢你的学习
data_frame1 <- data.frame(a=c(1,5,3,3,2), b=c(3,6,1,5,5), c=c(4,4,1,9,2))
data_frame2 <- data.frame(a=c(6,0,9,1,2), b=c(2,7,2,2,1), c=c(8,4,1,9,2))
data_frame3 <- data.frame(a=c(0,0,1,5,1), b=c(4,1,9,2,3), c=c(2,9,7,1,1))

ll <- list(data_frame1,data_frame2,data_frame3)
lapply(ll,function(df){
  df$log_a <- log(df$a)          ## new column with the log a
  df$tans_col <- df$a+df$b+df$c  ## new column with sums of some columns or any other           
                                 ##   transformation
  ###  .....
  df

})
[[1]]
  a b c     log_a tans_col
1 1 3 4 0.0000000        8
2 5 6 4 1.6094379       15
3 3 1 1 1.0986123        5
4 3 5 9 1.0986123       17
5 2 5 2 0.6931472        9
list2env(list_of_dataframes ,.GlobalEnv)