Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

melt with chron

I'm trying to melt a data frame with chron class

library(chron)
x = data.frame(Index = as.chron(c(15657.00,15657.17)), Var1 = c(1,2), Var2 = c(9,8))
x
                Index Var1 Var2
1 (11/13/12 00:00:00)    1    9
2 (11/13/12 04:04:48)    2    8

y = melt(x,id.vars="Index")
Error in data.frame(ids, variable, value, stringsAsFactors = FALSE) : 
  arguments imply differing number of rows: 2, 4

I can trick with as.numeric() as follows:

x$Index= as.numeric(x$Index)
y = melt(x,id.vars="Index")
y$Index = as.chron(y$Index)
y
                Index variable value
1 (11/13/12 00:00:00)     Var1     1
2 (11/13/12 04:04:48)     Var1     2
3 (11/13/12 00:00:00)     Var2     9
4 (11/13/12 04:04:48)     Var2     8

But can it be simpler ? (I want to keep the chron class)

like image 871
fRed Avatar asked May 05 '26 20:05

fRed


1 Answers

(1) I assume you issued this command before running the code shown:

library(reshape2)

In that case you could use the reshape package instead. It doesn't result in this problem:

library(reshape)

Other solutions are to

(2) use R's reshape function:

reshape(direction = "long", data = x, varying = list(2:3), v.names = "Var")

(3) or convert the chron column to numeric, use melt from the reshape2 package and then convert back:

library(reshape2)
xt <- transform(x, Index = as.numeric(Index))
transform(melt(xt, id = 1), Index = chron(Index))

ADDED additional solutions.

like image 148
G. Grothendieck Avatar answered May 08 '26 09:05

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!