Kore-N
Kore-N

Reputation: 145

Melt function with numerical entries in R

I have the following problem with the melt function in R (which is part of the reshape2 package).

Say I have the following example:

library(reshape2)
# I start with a matrix and create a data frame 
# who's first column is a numbering of the rows.
HH <- matrix(0, nrow = 10, ncol = 20)
df <- data.frame( pp = 1:10, HH)
# Then I melt it using the row number as a pivot (or id).
df <- melt(df ,  id.vars = 'pp', variable.name = 'time')

What I get is the right kind of matrix, but the "Time" data contains elements of the kind x1, ... , x2 and I would really like numerical values for later use (say 1,...,2). I suppose there must be some very intelligent way to achieve this, other than writing a code that changes the names of all the entries.

Upvotes: 1

Views: 1548

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193537

This might be a case where the "tidyverse" can help, specifically by using the convert argument in gather. I've also changed how you create the data.frame by adding a check.names = FALSE to the data.frame(...) step. Note, however, that you'll end up with syntactically invalid names with that approach, but since your target dataset structure is different, it shouldn't matter.

Example:

library(tidyverse)
df <- data.frame(pp = 1:10, HH, check.names = FALSE)
gather(df, key, value, -pp, convert = TRUE)

str(gather(df, key, value, -pp, convert = TRUE))
# 'data.frame': 200 obs. of  3 variables:
#  $ pp   : int  1 2 3 4 5 6 7 8 9 10 ...
#  $ key  : int  1 1 1 1 1 1 1 1 1 1 ...
#  $ value: num  0 0 0 0 0 0 0 0 0 0 ...

Upvotes: 2

Related Questions