【问题标题】:Pivot_wider: merge rows pairwisePivot_wider:成对合并行
【发布时间】:2021-08-17 22:02:10
【问题描述】:

我的tibble 如下所示:

    pic_type | dim1 | dim2 | dim3
    ------------------------------
    1          3       2     1
    1          5       5     6
    2          8       1     2
    2          5       1     1

我想合并pic_type 列中具有相同值的行。正好两行属于同一个图片类型!

所以结果应该如下所示:

    pic_type | dim1 | dim2 | dim3  | dim1 | dim2 | dim3
    ----------------------------------------------------
    1          3       2     1       5      5      6
    2          8       1     2       5      1      1

我该怎么做?

【问题讨论】:

    标签: r tidyverse tibble


    【解决方案1】:
    library(dplyr)
    library(tidyr)
    
    df %>%
      group_by(pic_type) %>%
      mutate(id = row_number()) %>%
      ungroup %>%
      pivot_wider(names_from = id, values_from = dim1:dim3)
    
    #  pic_type dim1_1 dim1_2 dim2_1 dim2_2 dim3_1 dim3_2
    #     <int>  <int>  <int>  <int>  <int>  <int>  <int>
    #1        1      3      5      2      5      1      6
    #2        2      8      5      1      1      2      1
    

    data.table -

    library(data.table)
    
    dcast(setDT(df), pic_type~rowid(pic_type), 
          value.var = grep('dim', names(df), value = TRUE))
    

    数据

    df <- structure(list(pic_type = c(1L, 1L, 2L, 2L), dim1 = c(3L, 5L, 
    8L, 5L), dim2 = c(2L, 5L, 1L, 1L), dim3 = c(1L, 6L, 2L, 1L)), 
    class = "data.frame", row.names = c(NA, -4L))
    

    【讨论】:

      【解决方案2】:

      我们也可以

      library(dplyr)
       library(data.table)
       library(tidyr)
       df %>%
           mutate(id = rowid(pic_type)) %>%
           pivot_wider(names_from = id, values_from = dim1:dim3)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-26
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        • 2017-05-23
        相关资源
        最近更新 更多