当前数据:
user_ID age_v1 age_v2 age_v3 gender visit score
1 63 65 67 M v1 8
1 63 65 67 M v2 4
1 63 65 67 M v3 1
我想要一个 tidyverse 解决方案来创建一个年龄列,其中的值与特定访问相对应。所需的输出,例如:
user_ID age gender visit score
1 63 M v1 8
1 65 M v2 4
1 67 M v3 1
注意:其他类似的解决方案(例如:如何在 R 中使用pivot_longer?)会导致数据集爆炸,从而创建许多重复行。请参阅对初始答案的回复(其作用相同)。
library(dplyr)
library(tidyr)
df %>%
pivot_longer(starts_with("age"), names_to = "x", values_to = "age") %>%
select(-x) %>%
relocate(age, .after = user_ID)
user_ID age gender visit score
<int> <int> <chr> <chr> <int>
1 1 63 M v1 8
2 1 65 M v1 8
3 1 67 M v1 8
4 1 63 M v2 4
5 1 65 M v2 4
6 1 67 M v2 4
7 1 63 M v3 1
8 1 65 M v3 1
9 1 67 M v3 1