从函数列表中提取特定函数列
pulling specific function columns from a list of functions
我正在自学更多地使用 tidyverse,因为我希望将来能够编写更清晰的代码。
我有这样的数据:
data <- as_tibble(data.frame(x = c(1,2,3,3,4),
y = c(3,4,4,2,5),
z = c(1,1,5,5,3)))
我想获得所有 3 列的均值、标准差和置信区间。
我希望使用的代码是这样的:
data %>%
summarize_at(vars(x:z), list(mean=mean, sd=sd, cilow = ci[2], cihigh = ci[3]))
其中 ci() 函数来自 gmodels 包。当通过 ci 传递单个变量时,您可以选择要查看的输出列,但是当它是函数列表的一部分时,我得到错误
Error in ci[2] : object of type 'closure' is not subsettable
任何 advice/suggestions 都已得到认可ci!我尽量不手动计算所有 CI(我的实际数据有更多变量需要计算)
我们可以使用 lambda 函数。此外,_at/_all
已弃用,取而代之的是 across
library(dplyr)
library(gmodels)
data %>%
summarise(across(x:z, list(mean = ~ mean(.x, na.rm = TRUE),
sd = ~ sd(.x, na.rm = TRUE),
cilow = ~ ci(.x)[2], cihigh = ~ ci(.x)[3])))
-输出
# A tibble: 1 × 12
x_mean x_sd x_cilow x_cihigh y_mean y_sd y_cilow y_cihigh z_mean z_sd z_cilow z_cihigh
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2.6 1.14 1.18 4.02 3.6 1.14 2.18 5.02 3 2 0.517 5.48
或 summarise_at
data %>%
summarize_at(vars(x:z), list(mean=mean, sd=sd, cilow = ~ ci(.)[2], cihigh = ~ ci(.x)[3]))
# A tibble: 1 × 12
x_mean y_mean z_mean x_sd y_sd z_sd x_cilow y_cilow z_cilow x_cihigh y_cihigh z_cihigh
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2.6 3.6 3 1.14 1.14 2 1.18 2.18 0.517 4.02 5.02 5.48
我正在自学更多地使用 tidyverse,因为我希望将来能够编写更清晰的代码。
我有这样的数据:
data <- as_tibble(data.frame(x = c(1,2,3,3,4),
y = c(3,4,4,2,5),
z = c(1,1,5,5,3)))
我想获得所有 3 列的均值、标准差和置信区间。
我希望使用的代码是这样的:
data %>%
summarize_at(vars(x:z), list(mean=mean, sd=sd, cilow = ci[2], cihigh = ci[3]))
其中 ci() 函数来自 gmodels 包。当通过 ci 传递单个变量时,您可以选择要查看的输出列,但是当它是函数列表的一部分时,我得到错误
Error in ci[2] : object of type 'closure' is not subsettable
任何 advice/suggestions 都已得到认可ci!我尽量不手动计算所有 CI(我的实际数据有更多变量需要计算)
我们可以使用 lambda 函数。此外,_at/_all
已弃用,取而代之的是 across
library(dplyr)
library(gmodels)
data %>%
summarise(across(x:z, list(mean = ~ mean(.x, na.rm = TRUE),
sd = ~ sd(.x, na.rm = TRUE),
cilow = ~ ci(.x)[2], cihigh = ~ ci(.x)[3])))
-输出
# A tibble: 1 × 12
x_mean x_sd x_cilow x_cihigh y_mean y_sd y_cilow y_cihigh z_mean z_sd z_cilow z_cihigh
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2.6 1.14 1.18 4.02 3.6 1.14 2.18 5.02 3 2 0.517 5.48
或 summarise_at
data %>%
summarize_at(vars(x:z), list(mean=mean, sd=sd, cilow = ~ ci(.)[2], cihigh = ~ ci(.x)[3]))
# A tibble: 1 × 12
x_mean y_mean z_mean x_sd y_sd z_sd x_cilow y_cilow z_cilow x_cihigh y_cihigh z_cihigh
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2.6 3.6 3 1.14 1.14 2 1.18 2.18 0.517 4.02 5.02 5.48