【问题标题】:Collapse / concatenate / aggregate a column to a single comma separated string within each group折叠/连接/聚合一列到每个组中的单个逗号分隔字符串
【发布时间】:2013-04-02 18:33:14
【问题描述】:

我想根据两个分组变量聚合数据框中的一列,并用逗号分隔各个值。

这是一些数据:

data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = rep(1:2, 3), C = c(5:10))
data
#     A B  C
# 1 111 1  5
# 2 111 2  6
# 3 111 1  7
# 4 222 2  8
# 5 222 1  9
# 6 222 2 10    

“A”和“B”是分组变量,“C”是我想折叠成逗号分隔的变量character字符串。我试过了:

library(plyr)
ddply(data, .(A,B), summarise, test = list(C))

    A B  test
1 111 1  5, 7
2 111 2     6
3 222 1     9
4 222 2 8, 10

但是当我尝试将测试列转换为character 时,它变成了这样:

ddply(data, .(A,B), summarise, test = as.character(list(C)))
#     A B     test
# 1 111 1  c(5, 7)
# 2 111 2        6
# 3 222 1        9
# 4 222 2 c(8, 10)

如何保持character 格式并用逗号分隔它们?例如,第 1 行应该只有 "5,7",而不是 c(5,7)。

【问题讨论】:

    标签: r aggregate r-faq


    【解决方案1】:

    这里有一些使用toString 的选项,该函数使用逗号和空格连接字符串向量以分隔组件。如果您不想使用逗号,则可以将 paste()collapse 参数一起使用。

    data.table

    # alternative using data.table
    library(data.table)
    as.data.table(data)[, toString(C), by = list(A, B)]
    

    聚合这不使用任何包:

    # alternative using aggregate from the stats package in the core of R
    aggregate(C ~., data, toString)
    

    sqldf

    这里是使用 SQL 函数 group_concat 的替代方法,使用 sqldf package

    library(sqldf)
    sqldf("select A, B, group_concat(C) C from data group by A, B", method = "raw")
    

    dplyr dplyr 替代方案:

    library(dplyr)
    data %>%
      group_by(A, B) %>%
      summarise(test = toString(C)) %>%
      ungroup()
    

    plyr

    # plyr
    library(plyr)
    ddply(data, .(A,B), summarize, C = toString(C))
    

    【讨论】:

    • 只保留唯一值:as.data.table(data)[, toString(unique(C)), by = list(A, B)]
    【解决方案2】:

    这里是stringr/tidyverse 解决方案:

    library(tidyverse)
    library(stringr)
    
    data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = rep(1:2, 3), C = c(5:10))
    
    
    data %>%
     group_by(A, B) %>%
     summarize(text = str_c(C, collapse = ", "))
    
    # A tibble: 4 x 3
    # Groups:   A [2]
          A     B text 
      <dbl> <int> <chr>
    1   111     1 5, 7 
    2   111     2 6    
    3   222     1 9    
    4   222     2 8, 10
    

    【讨论】:

    • 也可以将stringr::str_c 替换为基础R 中的paste
    【解决方案3】:

    更改您放置as.character的位置:

    > out <- ddply(data, .(A, B), summarise, test = list(as.character(C)))
    > str(out)
    'data.frame':   4 obs. of  3 variables:
     $ A   : num  111 111 222 222
     $ B   : int  1 2 1 2
     $ test:List of 4
      ..$ : chr  "5" "7"
      ..$ : chr "6"
      ..$ : chr "9"
      ..$ : chr  "8" "10"
    > out
        A B  test
    1 111 1  5, 7
    2 111 2     6
    3 222 1     9
    4 222 2 8, 10
    

    请注意,在这种情况下,每个项目实际上仍然是一个单独的字符,而不是单个字符串。也就是说,这不是一个看起来像“5, 7”的实际字符串,而是两个字符,“5”和“7”,R 用它们之间的逗号显示。

    与以下比较:

    > out2 <- ddply(data, .(A, B), summarise, test = paste(C, collapse = ", "))
    > str(out2)
    'data.frame':   4 obs. of  3 variables:
     $ A   : num  111 111 222 222
     $ B   : int  1 2 1 2
     $ test: chr  "5, 7" "6" "9" "8, 10"
    > out
        A B  test
    1 111 1  5, 7
    2 111 2     6
    3 222 1     9
    4 222 2 8, 10
    

    base R 中的类似解决方案当然是aggregate

    > A1 <- aggregate(C ~ A + B, data, function(x) c(as.character(x)))
    > str(A1)
    'data.frame':   4 obs. of  3 variables:
     $ A: num  111 222 111 222
     $ B: int  1 1 2 2
     $ C:List of 4
      ..$ 0: chr  "5" "7"
      ..$ 1: chr "9"
      ..$ 2: chr "6"
      ..$ 3: chr  "8" "10"
    > A2 <- aggregate(C ~ A + B, data, paste, collapse = ", ")
    > str(A2)
    'data.frame':   4 obs. of  3 variables:
     $ A: num  111 222 111 222
     $ B: int  1 1 2 2
     $ C: chr  "5, 7" "9" "6" "8, 10"
    

    【讨论】:

      【解决方案4】:

      这里有一个小的改进以避免重复

      # 1. Original data set
      data <- data.frame(
        A = c(rep(111, 3), rep(222, 3)), 
        B = rep(1:2, 3), 
        C = c(5:10))
      
      # 2. Add duplicate row
      data <- rbind(data, data.table(
        A = 111, B = 1, C = 5
      ))
      
      # 3. Solution with duplicates
      data %>%
        group_by(A, B) %>%
        summarise(test = toString(C)) %>%
        ungroup()
      
      #      A     B test   
      #   <dbl> <dbl> <chr>  
      # 1   111     1 5, 7, 5
      # 2   111     2 6      
      # 3   222     1 9      
      # 4   222     2 8, 10
      
      # 4. Solution without duplicates
      data %>%
        select(A, B, C) %>% unique() %>% 
        group_by(A, B) %>%
        summarise(test = toString(C)) %>%
        ungroup()
      
      #    A     B test 
      #   <dbl> <dbl> <chr>
      # 1   111     1 5, 7 
      # 2   111     2 6    
      # 3   222     1 9    
      # 4   222     2 8, 10
      

      希望对你有用。

      【讨论】:

        【解决方案5】:

        使用来自collapsecollap

        library(collapse)
        collap(data, ~ A + B, toString)
            A B     C
        1 111 1  5, 7
        2 111 2     6
        3 222 1     9
        4 222 2 8, 10
        

        数据

        data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = rep(1:2, 3), C = c(5:10))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-10
          • 2017-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-27
          • 2022-11-27
          相关资源
          最近更新 更多