【发布时间】:2018-05-12 07:41:51
【问题描述】:
我想同时对多个字符变量使用summarise_at 和mutate_at。我查看了许多使用整数变量的示例,但我无法弄清楚字符变量。下面是我用来为字符(或因子)变量生成描述性统计数据的代码。
library(tidyverse)
# First block of code
starwars %>%
group_by(gender) %>%
summarise (n = n()) %>%
mutate(totalN = (cumsum(n))) %>%
mutate(percent = round((n / sum(n)), 3)) %>%
mutate(cumpercent = round(cumsum(freq = n / sum(n)),3))
这会产生:
A tibble: 5 x 5
gender n totalN percent cumpercent
<chr> <int> <int> <dbl> <dbl>
1 female 19 19 0.218 0.218
2 hermaphrodite 1 20 0.011 0.230
3 male 62 82 0.713 0.943
4 none 2 84 0.023 0.966
5 <NA> 3 87 0.034 1.000
我想制作同样的东西,但同时用于多个字符(或因子)变量。在这种情况下,让我们使用变量gender 和eye_color 这是我尝试过的:
starwars %>%
summarise_at(vars(gender, eyecolor) (n = n()) %>%
mutate_at(vars(gender, eyecolor) (totalN = (cumsum(n))) %>%
mutate_at(vars(gender", "eyecolor) (percent = round((n / sum(n)), 3)) %>%
mutate_at(vars(gender, eyecolor) (cumpercent = round(cumsum(freq = n / sum(n)),3))))))
我收到以下错误:
Error in eval(expr, envir, enclos) : attempt to apply non-function
我知道有使用funs 调用的内置函数,但我不想使用它们。我尝试过以许多不同的方式使用代码以使其正常工作,但都失败了。
我想制作的是这样的:
A tibble: 5 x 5
gender n totalN percent cumpercent
<chr> <int> <int> <dbl> <dbl>
1 female 19 19 0.218 0.218
2 hermaphrodite 1 20 0.011 0.230
3 male 62 82 0.713 0.943
4 none 2 84 0.023 0.966
5 <NA> 3 87 0.034 1.000
A tibble: 15 x 5
eye_color n totalN percent cumpercent
<chr> <int> <int> <dbl> <dbl>
1 black 10 10 0.115 0.115
2 blue 19 29 0.218 0.333
3 blue-gray 1 30 0.011 0.345
4 brown 21 51 0.241 0.586
5 dark 1 52 0.011 0.598
6 gold 1 53 0.011 0.609
7 green, yellow 1 54 0.011 0.621
8 hazel 3 57 0.034 0.655
9 orange 8 65 0.092 0.747
10 pink 1 66 0.011 0.759
11 red 5 71 0.057 0.816
12 red, blue 1 72 0.011 0.828
13 unknown 3 75 0.034 0.862
14 white 1 76 0.011 0.874
15 yellow 11 87 0.126 1.000
也许循环会更好?现在我有很多行代码来为每个字符变量生成描述性统计信息,因为我必须为每个变量运行第一个代码块(如上所述)。如果我能列出我想使用的变量并在第一段代码中运行每个变量,那就太好了。
【问题讨论】:
-
您能否举例说明您想要的输出应该是什么样的?我怀疑你的问题是你需要
group_by(gender, eye_color),然后在你的第一个例子中使用mutate()调用,而不是使用mutate_at(),但也许我误解了你在找什么。 -
同意疯狂比利。在因子变量上使用
mutate_at意味着您想要对这些变量进行计算 - 但是没有为因子定义诸如cumsum和除法之类的东西。也许您想一次创建多个列?或者也许你只需要分组?没有样本输出无法判断。 (请注意,在您的第一个示例中,您只在group_by中使用了gender,而在mutate中根本没有使用它。)