在R中按组将 Dataframe 旋转得更长

inn6fuwd  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(107)

我有一个dataframe,看起来像这样:

example <- data.frame(
  Partner.A.s.ID = c(1101, 1102),
  Partner.A.s.name = c("X", "A"),
  Partner.B.s.ID = c(2101, 2102),
  Partner.B.s.name = c("Y", "B"),
  Partner.A.s.email = c("XXX", "AAA"),
  Partner.B.s.email = c("YYY", "BBB")
)

字符串
我如何按组(即(A和B)?这是所需的输出:

example_solution <- data.frame(
  Partner.ID = c(1101, 1102, 2101, 2102),
  Partner.name = c('X', 'A', 'Y', 'B'),
  Partner.email = c("XXX", "AAA", "YYY", "BBB")
)


谢谢你,谢谢

wgx48brx

wgx48brx1#

library(tidyr)

example <- data.frame(
  Partner.A.s.ID = c(1101, 1102),
  Partner.A.s.name = c("X", "A"),
  Partner.B.s.ID = c(2101, 2102),
  Partner.B.s.name = c("Y", "B"),
  Partner.A.s.email = c("XXX", "AAA"),
  Partner.B.s.email = c("YYY", "BBB")
)

pivot_longer(example, everything() , 
             names_to = c("A/B",".value"),
             names_pattern = "Partner.(.).s.(.*)")

#> # A tibble: 4 × 4
#>   `A/B`    ID name  email
#>   <chr> <dbl> <chr> <chr>
#> 1 A      1101 X     XXX  
#> 2 B      2101 Y     YYY  
#> 3 A      1102 A     AAA  
#> 4 B      2102 B     BBB

字符串
创建于2023-07-21使用reprex v2.0.2

相关问题