1

I'm trying to reshape a longitudinal dataset containing visual measurements for the left and right eyes of several individuals over a one year period. I need to end up with a data.frame() with the headings 'patient','month','re','le' (where 're' means 'right eye' and 'le' means 'left eye')

My data are currently in the format:

 patient','re_month1','le_month1','re_month2','le_month2'....'le_month12'

I know I could use the reshape() function to sort the data if I only had one piece of data per time point. If I were just working with 'patient','month1','month2' etc, I could use the following:

 reshape(dframe,idvar = 'patient',v.names = 'vision',
                       varying = 2:13,direction = "long")

...But how do I do this when there are two pieces of data (or more) at each time point?

akrun
  • 674,427
  • 24
  • 381
  • 486
CaptainProg
  • 5,188
  • 22
  • 67
  • 109
  • please share example of your data and format code chunks – mtoto Jan 20 '16 at 10:14
  • 2
    you can use the varying argument to separate the left and right, by passing the column indices separately.. `varying=list(c(2,4), c(3,5))`, and so on for all the right and left indices. – user20650 Jan 20 '16 at 10:17

1 Answers1

1

We can use melt from data.table and specify the measure columns with the patterns argument. The patterns can take multiple regex/fixed column names.

 library(data.table)
 melt(setDT(dframe), id.var="patient", 
             measure = patterns("^re_", "^le_"))
 #    patient variable value1 value2
 #1:       1        1     20     21
 #2:       2        1     25     18
 #3:       3        1     23     22
 #4:       1        2     18     29
 #5:       2        2     22     19
 #6:       3        2     25     24

data

 dframe <- data.frame(patient=1:3, re_month1 = c(20, 25,
  23), le_month1= c(21, 18, 22), re_month2=c(18, 22, 25),
  le_month2= c(29, 19, 24))
akrun
  • 674,427
  • 24
  • 381
  • 486