make a df with a single observation but certain repeated columns

hello, I have a database where there are subjects with several observations and I would like to make a database where there is a single observation for each id

but I would like that for certain variables there are 2 columns (one for each value), how can it be done?

I put a reprex

this is similar to what I have

id a b c d e
1 1 2 3 4 4
2 1 2 3 5 1
2 1 2 3 4 1
3 1 2 3 6 2
4 1 2 3 1 3
5 1 2 3 2 4
5 1 2 3 3 5

And this is what I want

id a b c d_1 d_2 e_1 e_2
1 1 2 3 4 4
2 1 2 3 5 4 1 1
3 1 2 3 6 2
4 1 2 3 1 3
5 1 2 3 2 3 4 5

Here's how I would do this:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyr)

examp <- tibble(
  id = c(1, 2, 2, 3, 4, 5, 5),
  a = c(1, 1, 1, 1, 1, 1, 1), 
  b = c(2, 2, 2, 2, 2, 2, 2), 
  c = c(3, 3, 3, 3, 3, 3, 3), 
  d = c(4, 5, 4, 6, 1, 2, 3), 
  e = c(4, 1, 1, 2, 3, 4, 5))

examp %>%
  group_by(id) %>%
  mutate(Row=row_number()) %>%
  ungroup() %>%
  pivot_wider(
    values_from=c(d, e),
    names_from=Row
  )
#> # A tibble: 5 × 8
#>      id     a     b     c   d_1   d_2   e_1   e_2
#>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1     1     1     2     3     4    NA     4    NA
#> 2     2     1     2     3     5     4     1     1
#> 3     3     1     2     3     6    NA     2    NA
#> 4     4     1     2     3     1    NA     3    NA
#> 5     5     1     2     3     2     3     4     5

Created on 2025-04-14 with reprex v2.1.1

1 Like