TonyGW TonyGW - 2 months ago 13
R Question

R: reshaping data frame to long data format with reshape2

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!

Answer

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

There's also quite a bit of documentation on reshaping data too