代码之家  ›  专栏  ›  技术社区  ›  Rnovice

根据[重复]列中的唯一值在R中聚合

  •  2
  • Rnovice  · 技术社区  · 7 年前

    我有一个数据帧 df 有三列 item , store week . 看起来是这样的:

     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
    

    我想看看每个人 项目 存在于多少 百货商店 . 我尝试了以下方法:

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

    和功能 summaryBy 在里面 doBy 包裹:

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

    但是,功能 length 返回的数量 百货商店 重复计算,即,它对每个 百货商店 对于每个 . 如何避免这种重复计算并获得唯一长度 百货商店 对于每个 项目 ?

    1 回复  |  直到 7 年前
        1
  •  2
  •   akrun    7 年前

    我们需要得到 length unique 元素

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

    或者如果我们正在使用 dplyr

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