【问题标题】:How do I compute the frequency/table of categorical variables by group with R data.table? [duplicate]如何使用 R data.table 按组计算分类变量的频率/表? [复制]
【发布时间】:2017-11-06 12:10:47
【问题描述】:

我有以下带有 R 的 data.table

library(data.table)
dt = data.table(ID = c("person1", "person1", "person1", "person2", "person2", "person2", "person2", "person2", ...), category = c("red", "red", "blue", "red", "red", "blue", "green", "green", ...))

dt
ID         category
person1    red
person1    red
person1    blue
person2    red
person2    red
person2    blue
person2    green
person2    green
person3    blue
....

我正在寻找如何为每个唯一 ID 创建分类变量 redbluegreen 的“频率”,然后展开这些列以记录每个的计数。生成的 data.table 如下所示:

dt
ID        red    blue    green
person1   2      1       0
person2   2      1       2    
...

我错误地认为以data.table 开头的正确方法是按组计算table(),例如

dt[, counts :=table(category), by=ID]

但这似乎是按组 ID 计算分类值的总数。这也不能解决我“扩展”data.table 的问题。

这样做的正确方法是什么?

【问题讨论】:

    标签: r dataframe data.table frequency


    【解决方案1】:

    像这样?

    library(data.table)
    library(dplyr)
    dt[, .N, by = .(ID, category)] %>% dcast(ID ~ category)
    

    如果你想将这些列添加到原来的data.table

    counts <- dt[, .N, by = .(ID, category)] %>% dcast(ID ~ category) 
    counts[is.na(counts)] <- 0
    output <- merge(dt, counts, by = "ID")
    

    【讨论】:

    • 这行得通!一个问题(因为我对dpylr 不太熟悉):假设原来的dt 有几列:如果我想保留另一列怎么办?目前,dcast(ID ~ category) 生成一个只有 ID 和类别的 data.table(如我的示例中所示)。
    • 查看我的编辑。您可以将表格数据合并到原始数据中。
    【解决方案2】:

    你可以用一行来使用reshape库。

    library(reshape2)
    dcast(data=dt,
          ID ~ category,
          fun.aggregate = length,
          value.var = "category")
    
           ID blue green red
    1 person1    1     0   2
    2 person2    1     2   2
    

    另外如果你只需要一个简单的 2-way table,你可以使用内置的 R table 函数。

    table(dt$ID,dt$category)

    【讨论】:

      【解决方案3】:

      这是以命令式风格完成的,可能有一种更简洁、更实用的方式。

      library(data.table)
      library(dtplyr)
      dt = data.table(ID = c("person1", "person1", "person1", "person2", "person2", "person2", "person2", "person2"), 
                      category = c("red", "red", "blue", "red", "red", "blue", "green", "green"))
      
      
      ids <- unique(dt$ID)
      categories <- unique(dt$category)
      counts <- matrix(nrow=length(ids), ncol=length(categories))
      rownames(counts) <- ids
      colnames(counts) <- categories
      
      for (i in seq_along(ids)) {
        for (j in seq_along(categories)) {
          count <- dt %>%
            filter(ID == ids[i], category == categories[j]) %>%
            nrow()
      
          counts[i, j] <- count
        }
      }
      

      然后:

      >counts
      ##         red blue green
      ##person1   2    1     0
      ##person2   2    1     2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多