在R中转换成频率table

Convert into frequency table in R

我有一个 table 像 :

> dt <- data.frame(C1 = c("one", "two", "one"), C2 = c("one", "two", "two"))
> dt
   C1  C2
1 one one
2 two two
3 one two

现在我需要上面的 table:

> dt <- data.frame(var = c("one", "two"), C1 = c(2, 1), C2 = c(1, 2))
> dt
  var C1 C2
1 one  2  1
2 two  1  2

我尝试了各种方法things/functions但无法得到结果。

使用 tidyverse 的一个选项是将 gather 转换为 'long' 格式,将 countspread 返回到 'wide'

library(dplyr)
library(tidyr)
gather(dt, key, val) %>%
      count(key, val) %>%
      spread(key, n)
# A tibble: 2 x 3
#  val      C1    C2
#* <chr> <int> <int>
#1 one       2     1
#2 two       1     2

如果我们只对频率感兴趣,那么使用 summarise_alltabulate

dt %>%
    summarise_all(funs(list(tabulate(.)))) %>% 
    unnest 

或使用base R

sapply(dt, table)

这是一个使用基础 R 的解决方案,当 table 中的某些因素未出现在每一列中时,该解决方案将起作用。

> dt <- data.frame(C1 = c("one", "two", "one", "one"), C2 = c("one", "two", "two", "three"))
> dt
   C1    C2
1 one   one
2 two   two
3 one   two
4 one three
> globalLevels <- as.character(unique(unlist(dt)))
> as.data.frame(lapply(dt, function(x) summary(factor(x, globalLevels))))
      C1 C2
one    3  1
two    1  2
three  0  1

下面还有一个解决方案:
1. 使用 reshape lib
融化数据 2. 创建 table 并转置(因为 melting 将变量 var 放在前面)

> dt <- data.frame(C1 = c("one", "two", "one"), C2 = c("one", "two", "two"))
> dt

   C1  C2
1 one one
2 two two
3 one two

> library(reshape)
> t(table(melt(dt, measure.vars = c("C2", "C1"))))

     variable
value C2 C1
  one  1  2
  two  2  1