在R中统计每列出现的次数

4

你好,我需要计算每列中每个数字的出现次数。以下是示例数据框:

A   B   C
2   1   2
2   1   1
1   1   3
3   3   3
3   2   2
2   1   2

我希望我的输出看起来像这样

how_much  A   B   C
1         1   4   1
2         3   1   3
3         2   1   2
4个回答

5
在tidyverse中,您可以这样做:
库(tidyverse)
gather(df1) %>%
  group_by(key,value) %>%
  count() %>%
  pivot_wider(value, names_from = key, values_from = n, values_fill = 0)

value     A     B     C
  <int> <int> <int> <int>
1     1     1     4     1
2     2     3     1     3
3     3     2     1     2

4
为了使解决方案更加灵活,可以应用purrr包中的函数来处理任何数字的情况。
library(dplyr)
library(purrr)

df1 %>%
  map(~ unique(.x) %>% sort()) %>% reduce(~ union(..1, ..2)) %>% 
  bind_cols(map_dfr(., ~ map_dfc(df1, function(a) sum(a == .x)))) %>%
      rename(what = ...1)

# A tibble: 3 x 4
   what     A     B     C
  <int> <int> <int> <int>
1     1     1     4     1
2     2     3     1     3
3     3     2     1     2

3

我们可以使用table标签。

table(unlist(df1), names(df1)[c(col(df1))])

-输出

    A B C
  1 1 4 1
  2 3 1 3
  3 2 1 2

或者使用sapply遍历列,并应用table
sapply(df1, table)
  A B C
1 1 4 1
2 3 1 3
3 2 1 2

数据

df1 <- structure(list(A = c(2L, 2L, 1L, 3L, 3L, 2L), B = c(1L, 1L, 1L, 
3L, 2L, 1L), C = c(2L, 1L, 3L, 3L, 2L, 2L)), 
     class = "data.frame", row.names = c(NA, 
-6L))

3

这个答案有点啰嗦,但适用于所有数据类型。

set.seed(1234)
df1 <- data.frame(A = sample(letters[1:3], 8, T),
                  B = sample(letters[1:3], 8, T),
                  C = sample(letters[1:3], 8, T))
df1
#>   A B C
#> 1 b c b
#> 2 b b a
#> 3 a b c
#> 4 c b c
#> 5 a c c
#> 6 a b a
#> 7 b b b
#> 8 b b a

library(tidyverse)

unique(unlist(apply(df1, 1, unique))) %>% as.data.frame() %>% setNames('how_much') %>%
  bind_cols(map_df(unique(unlist(apply(df1, 1, unique))), ~map_int(df1, \(x) sum(x %in% .x) ) ))

#>   how_much A B C
#> 1        b 4 6 2
#> 2        c 1 2 3
#> 3        a 3 0 3

使用reprex package(v2.0.0)于2021年6月23日创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接