POSIXct values become numeric in reshape2 dcast

后端 未结 3 1796
长情又很酷
长情又很酷 2021-01-12 23:55

I\'m trying to use dcast from the latest reshape2 package (1.2.1) to denormalize a data frame (or data.table) where the value.var is a POSIXct type, but in the resulting dat

3条回答
  •  终归单人心
    2021-01-13 00:17

    Doing debug(dcast) and debug(as.data.frame.matrix), then stepping through the calculations launched by your dcast() call will reveal that these lines in as.data.frame.matrix() are at fault:

    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])
    }
    

    The up-to-then POSIXct object has mode "numeric", so evaluation follows the second branch, which converts the results to numeric.

    If you use dcast(), it looks like you will need to post-process results, which shouldn't be too hard 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, base R's reshape() leaves POSIXct values as they are but will require you to edit the names of the resulting columns...

    reshape(d, idvar="x", timevar="y",  direction="wide")
    #   x                 z.c                 z.d
    # 1 a 2012-01-01 01:01:01                
    # 2 b                 2012-02-02 02:02:02
    

提交回复
热议问题