0

I am trying to play around with the mpg dataset in ggplot2, and I would like to convert the wide data format to long data format for the columns cty and hwy:

Wide/Original data format

manufacturer model cty hwy class
audi          a4    18  29   compact
audi          a4    21  28   compact

to this long data format:

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

I tried to use reshape2 to do this conversion:

mpg_long <- melt(mpg, id.vars=c("hwy", "cty"), variable.name="road_type", value.name="efficiency")

This does not work for me. I appreciate your help!

TonyGW
  • 16,995
  • 39
  • 101
  • 172

1 Answers1

1

I'm sure this is a duplicate question, but...

I think you had your id.vars mixed up

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
josliber
  • 43,000
  • 12
  • 95
  • 132
SymbolixAU
  • 23,954
  • 4
  • 56
  • 128