当使用创建按变量级别组织的摘要统计表时,我无法找到计算四分位数的语法,而不必重复列名。也就是说,使用调用,比如()和()与其他函数一起使用,例如()和(),但不与()一起使用。
搜索产生了过时的解决方案,因为它们使用已弃用的调用,例如()和/或()。
这段代码可以完美地输出我需要的结果,但是我想知道是否有更短的语法来避免重复使用变量。
搜索产生了过时的解决方案,因为它们使用已弃用的调用,例如()和/或()。
data(iris)
library(tidyverse)
#This works: Notice I have not attempted to calculate quartiles yet
summary_stat <- iris %>%
group_by(Species) %>%
summarise_at(vars(Sepal.Length),
list(min=min, median=median, max=max,
mean=mean, sd=sd)
)
A tibble: 3 x 6
Species min median max mean sd
<fct> <dbl> <dbl> <dbl> <dbl> <dbl>
1 setosa 4.3 5 5.8 5.01 0.352
2 versicolor 4.9 5.9 7 5.94 0.516
3 virginica 4.9 6.5 7.9 6.59 0.636
##########################################################################
#Does NOT work:
five_number_summary <- iris %>%
group_by(Species) %>%
summarise_at(vars(Sepal.Length),
list(min=min, Q1=quantile(.,probs = 0.25),
median=median, Q3=quantile(., probs = 0.75),
max=max))
Error: Must use a vector in `[`, not an object of class matrix.
Call `rlang::last_error()` to see a backtrace
###########################################################################
#This works: Remove the vars() argument, remove the list() argument,
#replace summarise_at() with summarise()
#but the code requires repeating the column name (Sepal.Length)
five_number_summary <- iris %>%
group_by(Species) %>%
summarise(min=min(Sepal.Length),
Q1=quantile(Sepal.Length,probs = 0.25),
median=median(Sepal.Length),
Q3=quantile(Sepal.Length, probs = 0.75),
max=max(Sepal.Length))
# A tibble: 3 x 6
Species min Q1 median Q3 max
<fct> <dbl> <dbl> <dbl> <dbl> <dbl>
1 setosa 4.3 4.8 5 5.2 5.8
2 versicolor 4.9 5.6 5.9 6.3 7
3 virginica 4.9 6.22 6.5 6.9 7.9
这段代码可以完美地输出我需要的结果,但是我想知道是否有更短的语法来避免重复使用变量。
~
的意义是什么?为什么只有quantile()
函数需要~
而其他函数不需要? - James~
是function(x){...}
的简写。如果没有它,R会尝试计算表达式quantile...
,但在这种情况下会失败。~
经常用于purrr
函数中,您可以在此处和此处找到更多信息。 - Arienrhod