rlong-integerwidechar

is there an R code for converting from wide to long when you have more than 1 unique id in R?


I have the following data that i want to convert from wide to long.

id_1<-c(1,2,2,2)
s02.0<-c(1,1,4,7)
s02.1<-c(2,2,5,8)
s02.2<-c(NA,3,6,NA)
id_2<-c(1,1,2,3)
df1<-data.frame(id_1,s02.0,s02.1,s02.2,id_2)

I would wish to have the following output based on two unique ids, and added new variable say n, that defines the position of 's02' in each row

id_1<-c(1,1,1,2,2,2,2,2,2,2,2,2)
id_2<-c(1,1,1,1,1,1,2,2,2,3,3,3)
s02<-c(1,2,NA,1,2,3,4,5,6,7,8,NA)
n<-c(1,2,3,1,2,3,1,2,3,1,2,3)
df2<-data.frame(id_1,id_2,s02,n)

Solution

  • We can use pivot_longer

    library(tidyr)
    library(dplyr)
    df1 %>% 
      pivot_longer(cols = starts_with('s02'), values_to = 's02') %>%    
      group_by(id_1, id_2) %>% 
      mutate(n = row_number())