Reputation: 15
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
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
isblank
then allnon-measured
variables will be used asid.vars
. Similarly, ifid.vars
is provided andmeasure.vars
isblank
then allnon id.vars
will be used asmeasure.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