当我在dplyr中使用group_by和summary时,我可以自然地将不同的汇总函数应用于不同的变量.例如:
library(tidyverse)
df <- tribble(
~category, ~x, ~y, ~z,
#----------------------
'a', 4, 6, 8,
'a', 7, 3, 0,
'a', 7, 9, 0,
'b', 2, 8, 8,
'b', 5, 1, 8,
'b', 8, 0, 1,
'c', 2, 1, 1,
'c', 3, 8, 0,
'c', 1, 9, 1
)
df %>% group_by(category) %>% summarize(
x=mean(x),
y=median(y),
z=first(z)
)
Run Code Online (Sandbox Code Playgroud)
结果输出:
# A tibble: 3 x 4
category x y z
<chr> <dbl> <dbl> <dbl>
1 a 6 6 8
2 b 5 1 8
3 c 2 8 1
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何使用summarise_at执行此操作?显然,对于这个例子来说这是不必要的,但假设我有很多变量,我想采取平均值,很多中位数等.
移动到summarise_at后,是否会丢失此功能?我是否必须在所有变量组上使用所有函数然后丢弃我不想要的变量?
也许我只是遗漏了一些东西,但我无法弄清楚,我在文档中没有看到任何这样的例子.任何帮助表示赞赏.
这是一个主意。
library(tidyverse)
df_mean <- df %>%
group_by(category) %>%
summarize_at(vars(x), funs(mean(.)))
df_median <- df %>%
group_by(category) %>%
summarize_at(vars(y), funs(median(.)))
df_first <- df %>%
group_by(category) %>%
summarize_at(vars(z), funs(first(.)))
df_summary <- reduce(list(df_mean, df_median, df_first),
left_join, by = "category")
Run Code Online (Sandbox Code Playgroud)
就像您说的那样,summarise_at
此示例无需使用。但是,如果您有很多列需要按不同的功能进行汇总,则此策略可能会起作用。您将需要在中指定vars(...)
每个列summarize_at
。规则与dplyr::select
功能相同。
这是另一个想法。定义一个修改该summarise_at
功能的功能,然后使用map2
该功能通过一个查找列表来应用此功能,该列表显示了要应用的变量和相关功能。在这个例子中,我施加mean
到x
与y
列和median
到z
。
# Define a function
summarise_at_fun <- function(variable, func, data){
data2 <- data %>%
summarise_at(vars(variable), funs(get(func)(.)))
return(data2)
}
# Group the data
df2 <- df %>% group_by(category)
# Create a look-up list with function names and variable to apply
look_list <- list(mean = c("x", "y"),
median = "z")
# Apply the summarise_at_fun
map2(look_list, names(look_list), summarise_at_fun, data = df2) %>%
reduce(left_join, by = "category")
# A tibble: 3 x 4
category x y z
<chr> <dbl> <dbl> <dbl>
1 a 6 6 0
2 b 5 3 8
3 c 2 6 1
Run Code Online (Sandbox Code Playgroud)
小智 6
由于您的问题是关于“summarise_at”;
我的想法是这样的:
df %>% group_by(category) %>%
summarise_at(vars(x, y, z),
funs(mean = mean, sd = sd, min = min),
na.rm = TRUE)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2521 次 |
最近记录: |