繁体   English   中英

R:将计算列添加到数据帧列表中

[英]R: add a calculated column to a list of dataframes

我有两个数据框列表。 我想在第一个列表上进行一些计算,然后将结果应用到第二个列表

# first list
df1 <- data.frame(id=1:5, score=c(rep(1, 3), rep(0, 2)))  
df2 <- data.frame(id=1:5, score=c(rep(1, 4), rep(0, 1)))
df1
   id score
1  1     1
2  2     1
3  3     1
4  4     0
5  5     0

df2
id score
1  1     1
2  2     1
3  3     1
4  4     1
5  5     0

list1 <- list(df1, df2)

# second list
df3 <- data.frame(id =1 :3)  
df4 <- data.frame(id =1 :4)    
list2 <- list(df3, df4)

我计算list1中每个数据帧的分数:

scores <- sapply(list1, function(df) sum(select(df, score))/nrow(df) )  
scores
[1] 0.6 0.8

现在我想用分数更新list2中的数据帧,以获得以下内容:第一个分数应用于第一个数据帧,第二个分数应用于第二个,依此类推。

df3
  id   score
1  1   0.6
2  2   0.6
3  3   0.6 

df4
  id   score
1  1   0.8
2  2   0.8
3  3   0.8
4  4   0.8 

我试过在list2上使用lapply,我正在考虑一些类似的东西

list2 <- lapply(list2, function(df){ df$score <- 1; df})  

显然有适当的分数而不是1.这会更新列表中的dfs,但是a)我无法让它更新数据帧df3和df4。 b)我看不出如何将计算得分传递给lapply函数

帮助赞赏。 TIA。

我们可以使用Map

Map(cbind, list2, score = scores)

暂无
暂无

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

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