【问题标题】:How to merge rows in a dataframe and combine factor-values in cells如何合并数据框中的行并合并单元格中的因子值
【发布时间】:2020-02-26 00:07:54
【问题描述】:

我在 R 中有一个数据框,我想在其中合并某些行并组合这些行中某些单元格的值。想象一下以下数据框:

Col.1<-c("a","b","b","a","c","c","c","d") Col.2<-c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm") df<-data.frame(Col.1, Col.2) df

Col.1 Col.2 a mouse b cat b dog a bird c giraffe c elephant c zebra d worm

我想合并 Col.1 中的值相同的所有相邻行,并相应地合并 Col.2 中的值。

最终的结果应该是这样的:

Col.1 Col.2 a mouse b cat dog a bird c giraffe elephant zebra d worm

我尝试使用 dplyr 解决方案(例如:ddply(df, .(Col.1), summarize, Col.2 = sum(Col.2))),但 sum-command 不适用于因子值。

【问题讨论】:

    标签: r dataframe merge rows


    【解决方案1】:

    编辑:错过了“相邻”位。请参阅下面来自this question 的使用基函数rle 的解决方案。

    Col.1 <- c("a","b","b","a","c","c","c","d")
    Col.2 <- c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm")
    df <- tibble(Col.1, Col.2)
    
    rlel <- rle(df$Col.1)$length
    df %>% 
      mutate(adj = unlist(lapply(1:length(rlel), function(i) rep(i, rlel[i])))) %>%
      group_by(Col.1, adj) %>% 
      summarize(New.Col.2 = paste(Col.2, collapse = " ")) %>%
      ungroup %>% arrange(adj) %>% select(-adj)
    
    # A tibble: 5 x 2
      Col.1 New.Col.2             
      <chr> <chr>                 
    1 a     mouse                 
    2 b     cat dog             
    3 a     bird             
    4 c     giraffe elephant zebra
    5 d     worm   
    

    【讨论】:

      【解决方案2】:

      我们可以通过粘贴进行分组。要对相邻的相似元素进行分组,可以使用data.table中的rleid,然后summarisepasteing中的'Col.2'的值

      library(dplyr)
      library(data.table)
      library(stringr)
      df %>%
          group_by(Col.1, grp = rleid(Col.1)) %>% 
          summarise(Col.2 = str_c(Col.2, collapse=' ')) %>%
          ungroup %>%
          select(-grp)
      # A tibble: 5 x 2
      #  Col.1 Col.2                 
      #  <fct> <chr>                 
      #1 a     mouse                 
      #2 a     bird                  
      #3 b     cat dog               
      #4 c     giraffe elephant zebra
      #5 d     worm         
      

      注意:这与 OP 帖子中显示的输出相匹配

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-16
        • 2019-11-30
        • 1970-01-01
        • 2014-11-22
        • 2021-02-14
        • 1970-01-01
        • 1970-01-01
        • 2016-11-30
        相关资源
        最近更新 更多