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

排列或dcast并填写计数

  •  0
  • dan  · 技术社区  · 3 年前

    可能是个基本问题。

    我有一个 key - value data.frame ( df (见下文):

    features <- paste0("f",1:5)
    set.seed(1)
    ids <- paste0("id",1:10)
    
    df <- do.call(rbind,lapply(ids,function(i){
      data.frame(id = i, feature = sample(features,3,replace = F))
    }))
    

    我想 tidyr::spread reshape2::dcast 将其删除,以便行被删除 id' the columns are 特色 , but the values are the sum of 特征 for each id`。

    reshape2::dcast(df, id ~ feature)
    

    但这并不能实现。它只是充满了 feature NA

    添加 fun.aggregate = sum 对上面的命令执行以下操作会导致错误:

    > reshape2::dcast(df, id ~ feature, fun.aggregate = sum)
    Using feature as value column: use value.var to override.
    Error in .fun(.value[0], ...) : invalid 'type' (character) of argument
    

    tidyr::spread(df, key = id, value = feature)
    
    Error: Each row of output must be identified by a unique combination of keys.
    Keys are shared for 30 rows:
    

    有什么想法吗?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Ronak Shah    3 年前

    我想你应该数一数功能,而不是 sum 他们尝试使用该函数 length .

    tidyr::pivot_wider(df, names_from = feature, 
                values_from = feature, values_fn = length, values_fill = 0)
    

    或与 dcast .

    library(data.table)
    dcast(setDT(df), id~feature, value.var = 'feature', fun.aggregate = length)
    

    table(df) 将给出相同的输出。

    table(df)
    
    #     feature
    #id     f1 f2 f3 f4 f5
    #  id1   1  0  1  1  0
    #  id10  1  0  1  1  0
    #  id2   1  1  0  0  1
    #  id3   0  1  1  1  0
    #  id4   1  0  1  0  1
    #  id5   1  1  0  0  1
    #  id6   1  1  1  0  0
    #  id7   1  0  0  1  1
    #  id8   1  1  0  0  1
    #  id9   0  1  0  1  1