pivot_longer 具有多个具有不同列名称模式和计数列的列

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

我查看了多个帖子,但没有看到这个确切的情况得到解决。

数据集目前看起来像这样

idno sex age_1 date_visit_1 height_in_cm_1 age_2 date_visit_2 height_in_cm_2 age_3 date_visit_3 height_in_cm_3

20   M   10    10/1/2010    100            11    10/1/2011    110             12   10/2/2012    115
21   F   11    10/2/2010    90             12    11/3/2011    100             13   12/5/2012    105
22   M   12    11/3/2010    100            13    12/4/2011    105             14   12/5/2012    110

我想要

idno sex age date_visit height_in_cm visit_no
20   M    10 10/1/2010 100           1
20   M    11 10/1/2011 110           2
20   M    12 10/2/2012 115           3
21   F    11 10/2/2010  90           1
21   F    12 11/3/2011 100           2
21   F    13 12/5/2012 105           3  
22   M    12 11/3/2010 100           1
22   M    13 12/4/2011 105           2
22   M    14 12/5/2012 110           3

我没能让它发挥作用。我要么得到两个相互堆叠的数据集,要么列名错误。由于变量名称的格式相似但不相同,names_pattern和names_sep对我没有帮助。

r reshape longitudinal
1个回答
0
投票

一种选择是暂时将数字变量更改为字符,这样您就可以将它们与访问日期一起

pivot

library(tidyr)
library(dplyr)

df |>
  mutate(across(c(starts_with('age'), starts_with('height')), as.character)) |>
  pivot_longer(c(-idno, -sex),
               names_to = c('stat', 'visit_no'),
               names_pattern = '^([a-zA-Z0-9]+_?[a-zA-Z0-9]+_?[a-zA-Z0-9]+)_([0-9]+)$',
               values_to = 'value') |>
  pivot_wider(names_from = stat, values_from = value) |>
  mutate(across(c(visit_no, age, height_in_cm), as.numeric),
         date_visit = as.Date(date_visit, format = '%m/%d/%y'))
#> # A tibble: 9 × 6
#>    idno sex   visit_no   age date_visit height_in_cm
#>   <int> <chr>    <dbl> <dbl> <date>            <dbl>
#> 1    20 M            1    10 2020-10-01          100
#> 2    20 M            2    11 2020-10-01          110
#> 3    20 M            3    12 2020-10-02          115
#> 4    21 F            1    11 2020-10-02           90
#> 5    21 F            2    12 2020-11-03          100
#> 6    21 F            3    13 2020-12-05          105
#> 7    22 M            1    12 2020-11-03          100
#> 8    22 M            2    13 2020-12-04          105
#> 9    22 M            3    14 2020-12-05          110

创建于 2024-04-18,使用 reprex v2.1.0

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.