Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name each variable using melt

Tags:

r

melt

reshape2

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?

like image 521
Josh R. Avatar asked Jul 13 '15 23:07

Josh R.


People also ask

What does melt () do in R?

The melt() function in R programming is an in-built function. It enables us to reshape and elongate the data frames in a user-defined manner. It organizes the data values in a long data frame format.

How do I rename a variable in R?

To rename an object or variable in R, just copy the data. frame variable to another variable by using the assignment operator (<- or =) and remove the existing variable using rm() function.

How do you melt data in R?

Melting in R It is performed using melt() function which takes dataset and column values that has to be kept constant. Using melt(), dataframe is converted into long format and stretches the data frame.

What does it mean to melt data?

The melt() function is used to convert a data frame with several measurement columns into a data frame in this canonical format, which has one row for every observed (measured) value.


1 Answers

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.

like image 104
mathematical.coffee Avatar answered Sep 29 '22 11:09

mathematical.coffee