JoeyMcDougalhauser
JoeyMcDougalhauser

Reputation: 15

melt multiple id.vars as all columns excluded from a list

df1<-data.frame(id=c("a","b","c","d"),
                var1=c(2,4,4,5),
                var2=c(5,6,2,6),
                var3=c(5,3,2,1))

msr<-c("var1", "var2","var3")

melt(df1,
 id.vars = -c(msr), #problem here
 measure.vars = c(msr))

I have a dataframe similiar to this, except with a large number of id.vars. I would like to include all of them and the easiest way would be to simply exclude columns used as measure.vars. However, I seem to be unable to this.

I have also tried:

ids<-df1[,-c(msr)] #why can't I exclude?
melt(df1,
     id.vars = c(ids), #problem here
     measure.vars = c(msr))

Any suggestions?

Upvotes: 1

Views: 8825

Answers (1)

MKR
MKR

Reputation: 20095

You don't need to specify the id.vars argument of reshape2::melt function if you know list of columns for measure.vars. The melt function is very much flexible in that sense:

Meaning if id.vars is blank then all non-measured variables will be used as id.vars. Similarly, if id.vars is provided and measure.vars is blank then all non id.vars will be used as measure.vars.

Hence, change needed to correct OP's use of melt is:

library(reshape2)

msr<-c("var1", "var2","var3")

melt(df1, measure.vars = msr)  # id.vars will be all non-measured variables

#    id variable value
# 1   a     var1     2
# 2   b     var1     4
# 3   c     var1     4
# 4   d     var1     5
# 5   a     var2     5
# 6   b     var2     6
# 7   c     var2     2
# 8   d     var2     6
# 9   a     var3     5
# 10  b     var3     3
# 11  c     var3     2
# 12  d     var3     1

Data:

df1<-data.frame(id=c("a","b","c","d"),
                var1=c(2,4,4,5),
                var2=c(5,6,2,6),
                var3=c(5,3,2,1))

Upvotes: 1

Related Questions