【问题标题】:Aggregate in R based on unique values in column [duplicate]根据列中的唯一值在 R 中聚合 [重复]
【发布时间】:2017-11-26 05:06:04
【问题描述】:

我有一个数据框df,其中包含三列itemstoreweek。它看起来像这样:

 item           store         week
24128          272568         1203
25554          272568         1203
24177          272568         1203
72000          272568         1203
72001          272568         1203
24128          272568         1204
25554          272568         1204
24177          272568         1204
72000          272568         1204
72001          272568         1204
-----          ------         ----
24128          272569         1203
25554          272569         1203
24177          272569         1203
72000          272569         1203
72001          272569         1203
24128          272569         1204
25554          272569         1204
24177          272569         1204
72000          272569         1204
72001          272569         1204

我想看看每个item 中存在多少store。我尝试了以下方法:

aggregate(store~item, data = df,FUN = "length")

以及doBy 包中的函数summaryBy

summaryBy(store~item,data = df,FUN = c(length))

但是,函数 length 返回 store 的数量并进行重复计数,即,它为每个 week 计算每个 store。如何避免这种重复计算并为每个 item 获得唯一的 store 长度?

【问题讨论】:

    标签: r aggregate


    【解决方案1】:

    我们需要在unique 元素上获取length

    aggregate(store~item, data = df,FUN = function(x) length(unique(x)))
    

    或者如果我们使用dplyr

    library(dplyr)
    df %>%
      group_by(item) %>%
      summarise(storen = n_distinct(store))
    

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多