r - 在多列上调用 dplyr::count 并以长格式 tibble 返回结果
问题描述
基本上我想这样做,但保持正确的排序顺序:
iris %>%
gather() %>%
group_by(key) %>%
count(value)
但是收集会丢弃属性,因此会丢失排序信息。
(通过排序我的意思是每个物种的计数应该是因子水平的顺序,每个数字的计数应该是数字顺序)。
因此,我认为我必须在调用收集之前嵌套所有列,以便每列成为一个包含一个(数据框)元素的列表。像这样的东西,但它不起作用:
iris %>%
summarise_all( function(x) nest(x)) %>%
gather() %>%
mutate( count_tibbles = map(data, key, function(x) x %>% count(key)))
有任何想法吗?
根据请求,我添加了所需输出的示例:
first_column_count = iris %>% count(value = Sepal.Length) %>% mutate( column_name = "Sepal.Length")
second_column_count = iris %>% count(value = Sepal.Width ) %>% mutate( column_name = "Sepal.Width" )
third_column_count = iris %>% count(value = Petal.Length) %>% mutate( column_name = "Petal.Length")
fourth_column_count = iris %>% count(value = Petal.Width ) %>% mutate( column_name = "Petal.Width" )
fifth_column_count = iris %>% count(value = Species ) %>% mutate( column_name = "Species" )
rbind(first_column_count, second_column_count, third_column_count, fourth_column_count, fifth_column_count) %>%
select(3,2,1)
顺便说一句,这与我的第一次尝试非常接近:
iris %>%
gather() %>%
group_by(key) %>%
count(value)
但这仅仅是因为 iris$Species 中的因子级别实际上是按字母顺序排序的。我正在寻找一种不按字母顺序排序的解决方案,这是我的第一次尝试,而是根据因子变量的因子水平和数字变量的数值(不是它们的字母值)对因子变量进行排序。因此,它也适用于因子水平不按字母顺序排列的情况。
解决方案
如果您排除Species
表单gather()
但将其包含在其中,group_by()
您可以保存物种排序。
iris %>%
gather(key='key', value = 'value', 1:4) %>%
group_by(Species, key) %>%
count(value)
如果将因子添加到键,则可以保持变量的顺序
iris %>%
gather(key='key', value = 'value', 1:4) %>%
mutate(key=factor(key, levels = names(iris[,1:4]))) %>%
group_by(Species, key) %>%
count(value)
所以输出看起来像
# A tibble: 175 x 4
# Groups: Species, key [12]
Species key value n
<fct> <fct> <dbl> <int>
1 setosa Sepal.Length 4.3 1
2 setosa Sepal.Length 4.4 3
3 setosa Sepal.Length 4.5 1
4 setosa Sepal.Length 4.6 4
5 setosa Sepal.Length 4.7 2
6 setosa Sepal.Length 4.8 5
7 setosa Sepal.Length 4.9 4
8 setosa Sepal.Length 5 8
9 setosa Sepal.Length 5.1 8
10 setosa Sepal.Length 5.2 3
# ... with 165 more rows
这是你想要的吗?