R语言 通过添加额外的列将2行折叠为一行

r3i60tvu  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(119)

我目前的数据格式为每id正好有2行。我想将这些行折叠成一个单行,如下所示。我试过使用pivot_wider(),但它给了我太多的列。我只想要两个专栏。我如何才能做到这一点?

# current structure
tibble::tribble(
  ~id,   ~n,             ~prop, ~name, ~value,
  "1", 135L, 0.918367346938776,  "q1",    "Y",
  "1", 135L, 0.918367346938776,  "q2",    "Y",
  "3", 225L, 0.945378151260504,  "q1",    "Y",
  "3", 225L, 0.945378151260504,  "q3",    "Y",
  "5", 446L, 0.944915254237288,  "q1",    "Y",
  "5", 446L, 0.944915254237288,  "q4",    "Y"
)
#> # A tibble: 6 x 5
#>   id        n  prop name  value
#>   <chr> <int> <dbl> <chr> <chr>
#> 1 1       135 0.918 q1    Y    
#> 2 1       135 0.918 q2    Y    
#> 3 3       225 0.945 q1    Y    
#> 4 3       225 0.945 q3    Y    
#> 5 5       446 0.945 q1    Y    
#> 6 5       446 0.945 q4    Y

# desired structure
tibble::tribble(
  ~id,   ~n,             ~prop, ~name1, ~value1, ~name2, ~value2,
  "1", 135L, 0.918367346938776,  "q1",    "Y",   "q2",    "Y",
  "3", 225L, 0.945378151260504,  "q1",    "Y",   "q3",    "Y",
  "5", 446L, 0.944915254237288,  "q1",    "Y",   "q4",    "Y"
)
#> # A tibble: 3 x 7
#>   id        n  prop name1 value1 name2 value2
#>   <chr> <int> <dbl> <chr> <chr>  <chr> <chr> 
#> 1 1       135 0.918 q1    Y      q2    Y     
#> 2 3       225 0.945 q1    Y      q3    Y     
#> 3 5       446 0.945 q1    Y      q4    Y

创建于2023 - 06 - 08使用reprex v2.0.2

i5desfxk

i5desfxk1#

library(dplyr)
library(tdiyr)
your_data |>
  mutate(id_row = row_number(), .by = "id") |>
  pivot_wider(names_from = id_row, values_from = c(name, value))
# # A tibble: 3 × 7
#   id        n  prop name_1 name_2 value_1 value_2
#   <chr> <int> <dbl> <chr>  <chr>  <chr>   <chr>  
# 1 1       135 0.918 q1     q2     Y       Y      
# 2 3       225 0.945 q1     q3     Y       Y      
# 3 5       446 0.945 q1     q4     Y       Y

相关问题