pivot_longer help

Hello,

I am looking at some of the pivot_longer code at the moment and just want to understand: 1) how best to keep variables while making the data longer and 2) to understand how I can drop variables within the everything() call and 3) some explanation on the arguments I can use for names_pattern and what exactly (.)(.) is doing?

library(tidyverse)

anscombe %>%
 pivot_longer(everything(),
   names_to = c(".value", "set"),
   names_pattern = "(.)(.)"
 )

#added in an ID variable I want to be retained to the corresponding rows and 
#added in an additional set of columns to make longer too

anscombe_test <- cbind(id = c(letters[1:11]), anscombe, z1 = c(1:11),z2 = c(11:21), z3 = c(31:41), z4 = c(51:61))

anscombe_test %>%
 pivot_longer(everything(),
   names_to = c(".value", "set"),
   names_pattern = "(.)(.)"
 )

anscombe_test %>%
  pivot_longer(-id,
               names_to = c(".value", "set"),
               names_pattern = "(.)(.)"
  )
1 Like

It'll be best if you provide a concrete example as there are many ways of doing this.

Only those variables you pass to the cols parameter will be pivoted. everything() is just a convenient shorthand to pivot all variables. You can pass variable names the same way you do with select().

names_pattern takes a regular expression. You can learn about them here. The () are used to capture matched groups (more about this on the website I linked).

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Thanks for this!

In terms of the keep, I just wanted to see how best to say keep a location variable in addition with id while doing the pivot_longer. From what you provided I should be fine though :slight_smile: