1

This is a very basic question, but I was wondering how I don't lose all the other columns in my dataset dt when I melt on the few melted variables. I want the other variables to remain in the dataset, with the same values they had in dt according to "eid". I had 3000 columns in dt, and now I only have 4: eid, variable, value1, and value2.

Preferably I would also be able to keep a select few columns from my dt and have it in my reshape dataset. Thanks!

reshape <- melt(dt, id.vars = "eid", measure.vars = patterns("^41202-0.", "^X41262.0."))

dt: 500,000 obs. on 3000 variables reshape: 33,000,000 obs. on 4 variables (would like a few more variables)

davidk
  • 133
  • 2
  • 11

1 Answers1

1

You can create a vector of the variables you want to keep as ids and pass it to the id.vars argument.

keep_vars = c("id1", "id2", ...)

reshape <- melt(dt, id.vars = keep_vars, 
  measure.vars = patterns("^41202-0.", "^X41262.0."))

This paper has some interesting examples that should help you understand the idea dcast and melt.

marbel
  • 7,560
  • 6
  • 49
  • 68