我正在尝试使用mpg
中的ggplot2
数据集,我想将宽数据格式转换为 cty 列的长数据格式的 HWY :
广泛/原始数据格式
manufacturer model cty hwy class
audi a4 18 29 compact
audi a4 21 28 compact
这种长数据格式:
manufacturer model variable value class
audi a4 cty 18 compact
audi a4 hwy 29 compact
audi a4 cty 21 compact
audi a4 hwy 28 compact
我尝试使用reshape2
进行此转换:
mpg_long <- melt(mpg, id.vars=c("hwy", "cty"), variable.name="road_type", value.name="efficiency")
这对我不起作用。感谢您的帮助!
答案 0 :(得分:1)
我确定这是一个重复的问题,但是......
我认为你的id.vars
混淆了
library(reshape2)
melt(mpg,
id.vars = c("manufacturer", "model","class"),
variable.name = "road_type",
value.name = "efficiency")
## or melt(mpg, measure.vars = c("cty","hwy"))
# manufacturer model class road_type efficiency
# 1 audi a4 compact cty 18
# 2 audi a4 compact cty 21
# 3 audi a4 compact hwy 29
# 4 audi a4 compact hwy 28