Pivot_wider:成对合并行

时间:2021-05-30 09:03:27

标签: r tidyverse tibble

我的 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

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

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))

答案 1 :(得分:0)

我们也可以

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