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

使用dplyr管道在R中连接时聚合

  •  0
  • val  · 技术社区  · 6 年前

    如何将数据帧从DF1分组并汇总到DF4?我希望以连接字符串的方式传播数据。我可以使用

    enter image description here 例子:

    DF1 <- data.frame(Owner = c("Owner A","Owner B","Owner C","Owner B","Owner D"),
                             Project = c("project AA","project BA","project CA","project BB","project DA"),
                             nWins = c(1,4,4,2,1),
                             Type = c("A","B","B","C","A"))
    DF1 %>% group_by(nWins, Type) %>% count %>% spread(Type,n) # to DF3
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   akuiper    6 年前

    而不是 count 使用 summarise 粘贴的步骤 Owner 根据字符串 nWins类型 然后 spread :

    DF1 %>% 
        group_by(nWins, Type) %>% 
        summarise(Owner = paste(Owner, collapse=";")) %>% 
        spread(Type, Owner, fill="") %>% 
        as.data.frame()
    
    #  nWins               A               B       C
    #1     1 Owner A;Owner D                        
    #2     2                                 Owner B
    #3     4                 Owner B;Owner C