zoukankan      html  css  js  c++  java
  • 【R】一对一变为一对多:将列折叠/连接/聚合为每个组(一行)内的字符串?

    需求

    原始文件:

    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
    1 111 1  5, 7
    2 111 2     6
    3 222 1     9
    4 222 2 8, 10
    

    通俗来说就是将一对一的关系折叠变为一对多的关系,中间用分隔符分开。

    实现

    方法一

    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
    

    查看下类型,折叠的列已变为数字列表。

    > str(x)
    'data.frame':	4 obs. of  3 variables:
     $ A   : num  111 111 222 222
     $ B   : int  1 2 1 2
     $ test:List of 4
      ..$ : int  5 7
      ..$ : int 6
      ..$ : int 9
      ..$ : int  8 10
    

    如要转变为字符串,直接用as.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)
    

    需要用toString函数。

    > z=ddply(data, .(A,B), summarize, C = toString(C));z
        A B     C
    1 111 1  5, 7
    2 111 2     6
    3 222 1     9
    4 222 2 8, 10
    > str(z)
    'data.frame':	4 obs. of  3 variables:
     $ A: num  111 111 222 222
     $ B: int  1 2 1 2
     $ C: chr  "5, 7" "6" "9" "8, 10"
    

    其他方法

    data.table

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

    dplyr

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

    aggregate

    aggregate(C ~., data, toString)
    

    sqldf

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

    延申:不用逗号分隔

    以上方法折叠后,都是默认逗号分隔,若是想用其他分隔符呢?可使用collapse参数指定,如dplyr方法:

    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
    

    Ref: https://stackoverflow.com/questions/15933958/collapse-concatenate-aggregate-a-column-to-a-single-comma-separated-string-w

  • 相关阅读:
    浅尝《Windows核心编程》之 等待函数
    linux 下 解压rar的过程
    一些多线程编程的例子(转)
    js数组操作《转》
    缩略图片处理<收藏>
    .net 框架
    详解NeatUpload上传控件的使用
    NHibernate工具
    xml xpath语法《转》
    C#事务技术
  • 原文地址:https://www.cnblogs.com/jessepeng/p/15048596.html
Copyright © 2011-2022 走看看