如何使用 R 中的管道运算符找到数据框一列的平均值?
How can I find the mean of one column of a data frame using a pipe operator in R?
我正在为我的 类 之一做作业。我们必须使用管道运算符来获取体积大于 13 的树的平均高度。
所以最初,我试过:
df <- trees
df %>% filter(Volume > 13) %>% mean(Height)
问题是,然后我收到一条警告信息
Warning message:
In mean.default(., Height) :
argument is not numeric or logical: returning NA
我无法弄清楚 Height 为什么不是数字(对我来说很明显它看起来像一个数字列表),所以我无法完成这个问题。
有人能帮帮我吗?我一直在测试不同的变体,但无济于事。
我们可以在summarise
内得到mean
library(dplyr)
df %>%
filter(Volume > 13) %>%
summarise(Mean = mean(Height))
mean
期望 vector
,如果我们需要在 summarise
pull
之外执行此操作,则 'Height' 为 vector
df %>%
filter(Volume > 13) %>%
pull(Height) %>%
mean
或使用.$Height
df %>%
filter(Volume > 13) %>%
.$Height %>%
mean
可以使用 iris
数据重现警告
data(iris)
iris %>%
mean(.$Sepal.Length)
#[1] NA
Warning message:
In mean.default(., .$Sepal.Length) :
argument is not numeric or logical: returning NA
与管道无关。如果输入是 data.frame,它 returns NA
因为期望是 vector
mean(iris['Sepal.Length'])
#[1] NA
Warning message:
In mean.default(iris["Sepal.Length"]) :
argument is not numeric or logical: returning NA
iris %>%
.$Sepal.Length %>%
mean
#[1] 5.843333
我正在为我的 类 之一做作业。我们必须使用管道运算符来获取体积大于 13 的树的平均高度。
所以最初,我试过:
df <- trees
df %>% filter(Volume > 13) %>% mean(Height)
问题是,然后我收到一条警告信息
Warning message:
In mean.default(., Height) :
argument is not numeric or logical: returning NA
我无法弄清楚 Height 为什么不是数字(对我来说很明显它看起来像一个数字列表),所以我无法完成这个问题。
有人能帮帮我吗?我一直在测试不同的变体,但无济于事。
我们可以在summarise
mean
library(dplyr)
df %>%
filter(Volume > 13) %>%
summarise(Mean = mean(Height))
mean
期望 vector
,如果我们需要在 summarise
pull
之外执行此操作,则 'Height' 为 vector
df %>%
filter(Volume > 13) %>%
pull(Height) %>%
mean
或使用.$Height
df %>%
filter(Volume > 13) %>%
.$Height %>%
mean
可以使用 iris
数据重现警告
data(iris)
iris %>%
mean(.$Sepal.Length)
#[1] NA
Warning message: In mean.default(., .$Sepal.Length) : argument is not numeric or logical: returning NA
与管道无关。如果输入是 data.frame,它 returns NA
因为期望是 vector
mean(iris['Sepal.Length'])
#[1] NA
Warning message: In mean.default(iris["Sepal.Length"]) : argument is not numeric or logical: returning NA
iris %>%
.$Sepal.Length %>%
mean
#[1] 5.843333