How to name each variable using melt

Josh R.  picture Josh R. · Jul 14, 2015 · Viewed 17.1k times · Source

I have a matrix that I want to reform for plotting in ggplo2 using the melt function from reshape2 but cannot find a way to add custom header names.

#Create toy data
MyData <- matrix(rnorm(15,500), nrow = 5, ncol = 3, dimnames = list(
    c("Unknown","0-4","4-9","10-14","15-19"),c("Area1","Area2","Area3")))

Dat2 <- melt(MyData, value.name = "Count")

#Reform data using melt, define Count as value name
MyData2 <- melt(MyData, value.name = "Count")

This gets me what I want but then operations that follow have to refer to the Var1 and Var2.

I tried naming them explicitly using variable.name:

MyData2 <- melt(MyData, value.name = "Count",
    variable.name = c("AgeGroup", "Geo"))

I can of course name them after the fact using colnames() but would like to do it using melt. Is this possible? Do I need to back up?

Answer

mathematical.coffee picture mathematical.coffee · Jul 14, 2015

Use varnames argument:

melt(MyData, value.name = "Count", varnames=c('AgeGroup', 'Geo'))
   AgeGroup   Geo    Count
1   Unknown Area1 501.6685
2       0-4 Area1 499.2812
3       4-9 Area1 500.3892
4     10-14 Area1 498.6380
5     15-19 Area1 500.5904
6   Unknown Area2 499.4590
7       0-4 Area2 500.5464
8       4-9 Area2 500.5635
9     10-14 Area2 500.7211
10    15-19 Area2 500.8381
11  Unknown Area3 498.8154
12      0-4 Area3 499.1818
13      4-9 Area3 499.6678
14    10-14 Area3 499.3586
15    15-19 Area3 500.3962

Your MyData is a matrix (so uses melt.array which uses varnames) not a dataframe (melt.data.frame uses variable.name). ?melt.array.