如何用均值替换相似组的值?

我这里有这个数据框

df = structure(list(D = c(-76, -74, -72, -70, -44, -42), A = c(83, 
83, 82, 82, 81, 81), B = c(-0.613, -0.4,-0.5, -0.68, -0.13, -0.26)), row.names = c(NA, 
 6L), class = "data.frame")

我想计算B中所有具有相似A值的平均值。

例如-0.613和-0.4,因为它们对应于相同的值83等。

评论
cut
cut

We can use aggregate from base R

aggregate(B ~ A, df, mean)

或者如果我们需要一个新列

df$Bmean <- with(df, ave(B, A))

Or with dplyr

library(dplyr)
df %>%
   group_by(A) %>%
   summarise(B = mean(B, na.rm = TRUE))

If we want to create a new column use mutate

df %>%
   group_by(A) %>%
   mutate(Bmean = mean(B, na.rm = TRUE))
点赞
评论