gpt4 book ai didi

重新格式化 dplyr summarise_at() 输出

转载 作者:行者123 更新时间:2023-12-05 09:13:57 25 4
gpt4 key购买 nike

我正在使用 summarise_at() 按组获取多个变量的均值和标准误差。

每组输出有 1 行,每个计算量有 1 列。我想要一个表,每个变量有 1 行,每个计算量有 1 列:

data <- mtcars 

data$condition <- as.factor(c(rep("control", 16), rep("treat", 16)))

data %>%
group_by(condition) %>%
summarise_at(vars(mpg, cyl, wt),
funs(mean = mean, se=sd(.)/sqrt(n())))

# A tibble: 2 x 7
condition mpg_mean cyl_mean wt_mean mpg_se cyl_se wt_se
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 control 18.2 6.5 3.56 1.04 0.387 0.204
2 treat 22.0 5.88 2.87 1.77 0.499 0.257

这是我认为更有用的(数字没有意义):

#        MEAN.control, MEAN.treat, SE.control, SE.treat
# mpg 1.5 2.4 .30 .45
# cyl 3.2 1.9 .20 .60
# disp 12.3 17.8 .20 .19

有什么想法吗? tidyverse 的新手,如果这太基础了,我们深表歉意。

最佳答案

funsdplyr 中被弃用。而是在 summarise_at/mutate_at 中使用 list。在 summarise 步骤之后,收集 数据为“long”格式,separate 通过在分隔符处拆分将“key”列一分为二 _,然后联合'cond'和'key2'(在改变'key2'的大小写之后),传播到'wide'格式和如果需要,使用“key1”列更改行名称

library(tidyverse)
data %>%
group_by(condition) %>%
summarise_at(vars(mpg, cyl, wt), list(MEAN = ~ mean(.),
SE = ~sd(.)/sqrt(n()))) %>%
gather(key, val, -condition) %>%
separate(key, into = c("key1", "key2")) %>%
unite(cond, key2, condition, sep=".") %>%
spread(cond, val) %>%
column_to_rownames('key1')
# MEAN.control MEAN.treat SE.control SE.treat
#cyl 6.500000 5.875000 0.3872983 0.4989572
#mpg 18.200000 21.981250 1.0369024 1.7720332
#wt 3.560875 2.873625 0.2044885 0.2571034

关于重新格式化 dplyr summarise_at() 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55209424/

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