R:使用 reshape2 将数据框重塑为长数据格式

R: reshaping data frame to long data format with reshape2

我正在尝试使用 ggplot2 中的 mpg 数据集,我想将宽数据格式转换为列 cty[ 的长数据格式=29=] 和 hwy:

Wide/Original数据格式

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

这对我不起作用。感谢您的帮助!

我确定这是一个重复的问题,但是...

我想你把 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