向数据框列表中添加计算列

4
我有两个数据框列表,希望对第一个列表进行一些计算,然后将结果应用于第二个列表。
# 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

现在我想用这些分数更新列表2中的数据框,以获取以下结果: 将第一个分数应用于第一个数据框,将第二个分数应用于第二个数据框,以此类推。

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。

1个回答

4
我们可以使用Map
Map(cbind, list2, score = scores)

天啊,这太简单了!但是我如何更新df3和df4,除了像 x <- Map(cbind, list2, score=scores); df3 <- x[[1]]; df4<- x[[2]] 这样的方法? - Garry
@Garry,最好将其保存在list中而不是更新原始对象。但如果您想要更新它,则可以使用list2 <- Map(cbind, list2, score = scores); names(list2) <- c("df3", "df4"); list2env(list2, .GlobalEnv) - akrun
1
非常感谢。太棒了! - Garry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接