`pivot_longer` operation - simpler way of achieving the expected output?

Viewed 75

I have a df of the form:

df <- tibble(
  id = c(1,2,3),
  val02 = c(0,1,0),
  val03 = c(1,0,0),
  val04 = c(0,1,1),
  age02 = c(1,2,3),
  age03 = c(2,3,4),
  age04 = c(3,4,5)
)

I want to bring it into tidy format like:

# A tibble: 9 x 4
     id year    val   age
  <dbl> <chr> <dbl> <dbl>
1     1 02        0     1
2     1 03        1     2
3     1 04        0     3
4     2 02        1     2
5     2 03        0     3
6     2 04        1     4
7     3 02        0     3
8     3 03        0     4
9     3 04        1     5

Using two seperate pivot_longer manipulations with a left_join at the end I achieved what I want:

library(tidyverse)
df1 <- df %>%
  pivot_longer(cols = starts_with("val"), names_to = "year", values_to = "val", names_prefix = "val")
df2 <- df %>%
  pivot_longer(cols = starts_with("age"), names_to = "year", values_to = "age", names_prefix = "age")

left_join(df1, df2) %>%
  select(id, year, val, age)

This, however, seems utterly complicated.

How can I simplify this operation? Is there a way to perform this operation in one go? (in one pipe..?)


1 Answers

This depends on the complexity of your strings (column names), but to give an idea:

library(tidyverse)

df %>%
  pivot_longer(-id,
               names_to = c('.value', 'year'),
               names_pattern = '([a-z]+)(\\d+)'
  )

Output:

# A tibble: 9 x 4
     id year    val   age
  <dbl> <chr> <dbl> <dbl>
1     1 02        0     1
2     1 03        1     2
3     1 04        0     3
4     2 02        1     2
5     2 03        0     3
6     2 04        1     4
7     3 02        0     3
8     3 03        0     4
9     3 04        1     5
Related