15

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?

Nakx
  • 1,460
  • 1
  • 23
  • 32
Josh R.
  • 449
  • 2
  • 4
  • 13

1 Answers1

21

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.

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
  • 2
    The solution above worked for renaming the variables but i am finding that the value.name does not work for naming the value. I feel like this worked before, looking at some past code i use for constructing diagnostic plots. The documentation only has varnames as a part of the function so is naming the value column not even possible? – Josh R. Sep 18 '15 at 16:32
  • The above code works for me (i.e. `value.name="Count"` names the 'value' column "Count"). – mathematical.coffee Sep 20 '15 at 12:05
  • Can't explain it, I used same code and got different results. It works now. Maybe rebooting my computer helped. Sorry for the needless question. (sign) – Josh R. Sep 21 '15 at 16:56
  • 1
    [Apparently](https://groups.google.com/d/msg/manipulatr/XP6MOotmY4Q/nEU1A3srpJ8J) you have to have reshape2 loaded making sure that reshape is detached?/ not loaded? Or more simply make sure to specify: `reshape2::melt(...` – CrunchyTopping Aug 01 '19 at 19:44
  • @CrunchyTopping That's it! – bathyscapher Jun 23 '20 at 09:19