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

醉酒当歌 提交于 2021-01-28 22:08:22

问题


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)

回答1:


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())


来源:https://stackoverflow.com/questions/63217608/is-there-an-r-code-for-converting-from-wide-to-long-when-you-have-more-than-1-un

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!