TonyGW TonyGW - 1 year ago 82
R Question

R: reshaping data frame to long data format with reshape2

I am trying to play around with the

dataset in
, 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
to do this conversion:

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

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

Answer Source

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

I think you had your id.vars mixed up


    id.vars = c("manufacturer", "model","class"), = "road_type", = "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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download