gpt4 book ai didi

r - summarise_at 对不同的变量使用不同的函数

转载 作者:行者123 更新时间:2023-12-04 03:56:25 25 4
gpt4 key购买 nike

当我在dplyr中使用group_by和summary时,自然可以对不同的变量应用不同的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)
)

结果输出:
    # 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

我的问题是,我将如何使用 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")

就像你说的,没有必要使用 summarise_at对于这个例子。但是,如果您有很多列需​​要按不同的功能进行汇总,则此策略可能会奏效。您需要在 vars(...) 中指定列每个 summarize_at .规则同 dplyr::select功能。

更新

这是另一个想法。定义一个函数来修改 summarise_at函数,然后使用 map2使用显示变量和要应用的关联函数的查找列表来应用此函数。在这个例子中,我申请了 meanxy列和 medianz .
# 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

关于r - summarise_at 对不同的变量使用不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46188208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com