melt
Convert an object into a molten data frame.
This the generic melt function. See the following functions for the details about different data structures:
- Keywords
- manip
Usage
melt(data, ..., na.rm = FALSE, value.name = "value")
Arguments
- data
Data set to melt
- ...
further arguments passed to or from other methods.
- na.rm
Should NA values be removed from the data set? This will convert explicit missings to implicit missings.
- value.name
name of variable used to store values
Details
melt.data.frame
for data.framesmelt.array
for arrays, matrices and tablesmelt.list
for lists
See Also
Community examples
x = data.frame( id = c(1, 1, 2, 2), color = c(1,1,1,1), blue = c(1, 0, 1, 0), red = c(0, 1, 0, 1) ) > x id color blue red 1 1 1 1 0 2 1 1 0 1 3 2 1 1 0 4 2 1 0 1 #collapse the dataframe retaining "id" and "color" and bringing "blue" and "red" from columns to rows > melt(data = x, id.vars = c("id", "color"), measure.vars = c("blue", "red")) id color variable value 1 1 1 blue 1 2 1 1 blue 0 3 2 1 blue 1 4 2 1 blue 0 5 1 1 red 0 6 1 1 red 1 7 2 1 red 0 8 2 1 red 1 Notice that, when you include "Id" and "color" in the "id.vars", these are retained as columns and whatever is mentioned in measure.vars is converted to rows with repeating values
x = data.frame( id = c(1, 1, 2, 2), color = c(1,1,1,1), blue = c(1, 0, 1, 0), red = c(0, 1, 0, 1) ) > x id color blue red 1 1 1 1 0 2 1 1 0 1 3 2 1 1 0 4 2 1 0 1 #collapse the dataframe retaining "id" and "color" and bringing "blue" and "red" from columns to rows > melt(data = x, id.vars = c("id", "color"), measure.vars = c("blue", "red")) id color variable value 1 1 1 blue 1 2 1 1 blue 0 3 2 1 blue 1 4 2 1 blue 0 5 1 1 red 0 6 1 1 red 1 7 2 1 red 0 8 2 1 red 1 Notice that, when you include "Id" and "color" in the "id.vars", these are retained as columns and whatever is mentioned in measure.vars is converted to rows with repeating values
library(reshape2) # example data frame x = data.frame( id = c(1, 1, 2, 2), blue = c(1, 0, 1, 0), red = c(0, 1, 0, 1) ) # collapse the data frame melt(data = x, id.vars = "id", measure.vars = c("blue", "red"))
library(reshape2) # example data frame x = data.frame( id = c(1, 1, 2, 2), blue = c(1, 0, 1, 0), red = c(0, 1, 0, 1) ) # collapse the data frame melt(data = x, id.vars = "id", measure.vars = c("blue", "red"))
##### Melt Example ```r library(reshape2) # example data frame x = data.frame( id = c(1, 1, 2, 2), blue = c(1, 0, 1, 0), red = c(0, 1, 0, 1) ) # collapse the data frame melt(data = x, id.vars = "id", measure.vars = c("blue", "red")) ```