POSIXct values ​​become numeric in reshape2 dcast

I am trying to use the dcast from the last (1.2.1) to denormalize a data frame (or data table), where value.var is a POSIXct type, but in the resulting data frame, the date values ​​have lost their POSIXct class and become numeric.

Do I really need, as .POSIXct (), each generated column if I want the values ​​returned as POSIXct, or am I missing something?

x <- c("a","b"); y <- c("c","d"); z <- as.POSIXct(c("2012-01-01 01:01:01","2012-02-02 02:02:02")); d <- data.frame(x, y, z, stringsAsFactors=FALSE); str(d); library(reshape2); e <- dcast(d, formula = x ~ y, value.var = "z"); str(e); 

The result of the execution on the operators (note that the new columns c and d represent the numeric seconds of the era instead of POSIXct):

 > x <- c("a","b"); > y <- c("c","d"); > z <- as.POSIXct(c("2012-01-01 01:01:01","2012-02-02 02:02:02")); > d <- data.frame(x, y, z, stringsAsFactors=FALSE); > str(d); 'data.frame': 2 obs. of 3 variables: $ x: chr "a" "b" $ y: chr "c" "d" $ z: POSIXct, format: "2012-01-01 01:01:01" "2012-02-02 02:02:02" > library(reshape2); > e <- dcast(d, formula = x ~ y, value.var = "z"); > str(e); 'data.frame': 2 obs. of 3 variables: $ x: chr "a" "b" $ c: num 1.33e+09 NA $ d: num NA 1.33e+09 
+6
source share
2 answers

Performing debug(dcast) and debug(as.data.frame.matrix) , then, after passing the calculations started by your dcast() call, it will find that these lines in as.data.frame.matrix() are in malfunction:

 if (mode(x) == "character" && stringsAsFactors) { for (i in ic) value[[i]] <- as.factor(x[, i]) } else { for (i in ic) value[[i]] <- as.vector(x[, i]) } 

There is a "numeric" mode in the current POSIXct object, so the evaluation follows the second branch, which converts the results to numeric.

If you use dcast() , it looks like you will need results after processing, which should not be too complicated if you have the correct origin . Something like this (which doesn't quite get the origin right) should do the trick:

 e[-1] <- lapply(e[-1], as.POSIXct, origin="1960-01-01") 

FWIW, the base of R reshape() leaves the POSIXct values ​​as they are, but will require you to edit the names of the received columns ...

 reshape(d, idvar="x", timevar="y", direction="wide") # x zc zd # 1 a 2012-01-01 01:01:01 <NA> # 2 b <NA> 2012-02-02 02:02:02 
+9
source

I just ran into this problem. I solved this by first entering the date field in the character, then dcast, and then returning to the date.

0
source

Source: https://habr.com/ru/post/924675/


All Articles