I have longitudinal data in a wide format that I am trying to convert to long format:
#I have a wide data which look like this:
dat_wide <- read.table(text="
cid dyad f1 f2 op2 ed1 junk
1 2 0 0 4 5 0.876
1 5 0 1 4 4 0.765
", header=TRUE)
#I want to convert it to long like this:
dat_long <- read.table(text="
cid dyad f op ed junk Visit
1 2 0 NA 5 0.876 1
1 2 0 4 NA 0.876 2
1 5 0 NA 4 0.765 1
1 5 1 4 NA 0.765 2
", header=TRUE)
#R code I was trying:
dat_l2 = reshape(dat_wide,idvar='cid', varying=list(c('f1','f2'), 'op2','ed1'),
#timevar='Visit',
times=c(1,2),
v.names=c('f','op','ed'),
direction='long')
#gives error:Error in reshape(merge_wide1, idvar = "cid", varying = c("f1", : length of 'v.names' does not evenly divide length of 'varying'
it's similar to Converting data from wide to long (using multiple columns)
The difference in my data is: I have some variables that were only recorded for fewer time points. eg.variable 'f' was recorded from both time 1 & time 2 but variable 'op' was recorded only for time2 (i.e. op2)& variable 'ed' was recorded only for time1 (i.e.ed1) head(data)