基于 R 中的 3 列整理透视表[重复]

问题描述 投票:0回答:1

当前数据:

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?)会导致数据集爆炸,从而创建许多重复行。请参阅对初始答案的回复(其作用相同)。

r pivot tidyr
1个回答
1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.