融化多个 id.vars 因为所有列都从列表中排除

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))

我有一个与此类似的数据框,除了有大量 id.vars。我想包括所有这些,最简单的方法是简单地排除用作 measure.vars 的列。不过这个我好像做不到。

我也试过:

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

有什么建议吗?

如果您知道 measure.vars 的列列表,则无需指定 reshape2::melt 函数的 id.vars 参数。 melt 函数在这个意义上非常灵活:

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.

因此,纠正 OP 对 melt 的使用所需的更改是:

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

数据:

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))