简体   繁体   English

r中不同数据帧的列的平均值

[英]Mean of columns of different dataframes in r

df1 <- data.frame(id=c(1,2,3,4,5,6),val1=c(1,2,3,NA,NA,6))
df2 <- data.frame(id=c(3,4,7,6,8) , val1=c(1,2,3,4,5))

Now what want is to combine the values of val1 from df1 and df2 as mean values which would be the df1$val1 . 现在想要的是将来自df1和df2的val1的值组合为平均值,即df1$val1 For example: 例如:

df1$val1 <- mean(df1$val1,df2$val2, na.rm=TRUE) & match(by=id)

df1$val1 should be the following df1$val1应该如下

val1
1
2
2((3+1)/2)
4(4+NA/2)
NA
6

We coudl try 我们试试吧

library(data.table)
rbindlist(list(df1, df2))[, .(val1 = mean(val1, na.rm = TRUE)), id][id %in% df1$id]

Or another option is 或者另一个选择是

setDT(df1)[df2, val1 := rowMeans(cbind(val1, i.val1), na.rm = TRUE), on = .(id)]

Or as @Frank mentioned in the comments 或者@Frank在评论中提到

setDT(df1); setDT(df2)
df1[, v := df2[df1, on=.(id), mean(c(x.val1, i.val1),
          na.rm=TRUE), by=.EACHI]$V1]

My solution using tidy. 我的解决方案使用整洁。

library(dplyr)
df1 <- data.frame(id=c(1,2,3,4,5,6),val1=c(1,2,3,NA,NA,6))
df2 <- data.frame(id=c(3,4,7,6,8) , val1=c(1,2,3,4,5))

df1 %>% left_join(df2, by="id") %>% select(2:3) %>% 
  transmute(val1=rowMeans(., na.rm=T))

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

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