我目前的数据格式为每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
1条答案
按热度按时间i5desfxk1#