我知道如何使用melt
的两个id.vars。这很简单:
x = data.frame(subject = c("John", "Mary"),
time = c(1,1),
age = c(33,35),
weight = c(90, 67),
height = c(2,2))
melt(x, id.vars = c('subject', 'time'), measure.vars = c('age', 'weight', 'height'))
# subject time variable value
#1 John 1 age 33
#2 Mary 1 age 35
#3 John 1 weight 90
#4 Mary 1 weight 67
#5 John 1 height 2
#6 Mary 1 height 2
但我怎样才能对key
使用两个id.vars或gather
}?
gather(data, key, value, ..., na.rm = FALSE, convert = FALSE,
factor_key = FALSE)
我只能设法使用一个key
。
答案 0 :(得分:4)
您还可以使用-
符号指定要保留的变量:
gather(x, variable, value, -c(subject,time))
答案 1 :(得分:2)
我们可以通过单独指定列,或者如果它们使用:
,或者使用列索引
library(tidyr)
gather(x, variable, value, age:height)
# subject time variable value
#1 John 1 age 33
#2 Mary 1 age 35
#3 John 1 weight 90
#4 Mary 1 weight 67
#5 John 1 height 2
#6 Mary 1 height 2
将从melt
reshape2
相同的输出
melt(x, id.vars = c('subject', 'time'), measure.vars = c('age', 'weight', 'height'))
# subject time variable value
#1 John 1 age 33
#2 Mary 1 age 35
#3 John 1 weight 90
#4 Mary 1 weight 67
#5 John 1 height 2
#6 Mary 1 height 2