R 无法使用聚合函数正确计算均值
R won't compute means correctly with aggregate function
不确定为什么 R 不能正确计算我的数据的均值。我确实有很多 NA 值,但 R 一直告诉我平均值是 NA。这是一个例子:
data1=read_excel"pepper.xlsx"
data1$cultivar = as.factor(data1$cultivar)
mean = aggregate(data1[,3:4], list(data1$cultivar), mean)
cultivar
replication
width
height
BOF
1
12
14
BOF
2
10
NA
BOF
3
NA
15
BOF
4
NA
NA
不是计算 BOF
的平均宽度为 11 和平均 height
为 14.5,而是计算高度和宽度的平均值为 NA。这是对我的数据的过度简化。我的研究中有几个品种,并使用 aggregate
函数计算了每个品种的每个变量的均值。
更新:
不需要匿名函数(致 Gregor Thomas,请参阅评论)。我们可以使用:
summarise(across(where(is.numeric), mean, na.rm = TRUE))
第一个回答:
感谢 Gregor Thomas colMeans
不会在这里工作。
我们可以使用 dplyr
包 summarise
和 across
library(dplyr)
df %>%
group_by(cultivar) %>%
summarise(across(where(is.numeric),~ mean(., na.rm = TRUE)))
输出:
cultivar replication width height
<chr> <dbl> <dbl> <dbl>
1 BOF 2.5 11 14.5
试试这个:
mean = aggregate(data1[,3:4], list(data1$cultivar), mean, na.rm = TRUE, na.action = na.pass)
不确定为什么 R 不能正确计算我的数据的均值。我确实有很多 NA 值,但 R 一直告诉我平均值是 NA。这是一个例子:
data1=read_excel"pepper.xlsx"
data1$cultivar = as.factor(data1$cultivar)
mean = aggregate(data1[,3:4], list(data1$cultivar), mean)
cultivar | replication | width | height |
---|---|---|---|
BOF | 1 | 12 | 14 |
BOF | 2 | 10 | NA |
BOF | 3 | NA | 15 |
BOF | 4 | NA | NA |
不是计算 BOF
的平均宽度为 11 和平均 height
为 14.5,而是计算高度和宽度的平均值为 NA。这是对我的数据的过度简化。我的研究中有几个品种,并使用 aggregate
函数计算了每个品种的每个变量的均值。
更新: 不需要匿名函数(致 Gregor Thomas,请参阅评论)。我们可以使用:
summarise(across(where(is.numeric), mean, na.rm = TRUE))
第一个回答:
感谢 Gregor Thomas colMeans
不会在这里工作。
我们可以使用 dplyr
包 summarise
和 across
library(dplyr)
df %>%
group_by(cultivar) %>%
summarise(across(where(is.numeric),~ mean(., na.rm = TRUE)))
输出:
cultivar replication width height
<chr> <dbl> <dbl> <dbl>
1 BOF 2.5 11 14.5
试试这个:
mean = aggregate(data1[,3:4], list(data1$cultivar), mean, na.rm = TRUE, na.action = na.pass)