3

我正在尝试使用 chron 类融化数据框

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

我可以欺骗as.numeric()如下:

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

但它可以更简单吗?(我想保留 chron 类)

4

2 回答 2

2

(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.

于 2013-03-26T16:33:16.670 回答
1

我不确定,但我认为这可能是一个“疏忽” 或者可能data.frame,但这似乎不太可能)。

melt.data.framereshape2中构建数据框时会出现此问题,该数据框通常使用回收,但以下部分data.frame

for (j in seq_along(xi)) {
    xi1 <- xi[[j]]
    if (is.vector(xi1) || is.factor(xi1)) 
        xi[[j]] <- rep(xi1, length.out = nr)
    else if (is.character(xi1) && class(xi1) == "AsIs") 
        xi[[j]] <- structure(rep(xi1, length.out = nr), class = class(xi1))
    else if (inherits(xi1, "Date") || inherits(xi1, "POSIXct")) 
        xi[[j]] <- rep(xi1, length.out = nr)
    else {
        fixed <- FALSE
        break
    }

似乎出错了,因为 chron 变量既不继承 Date 也不继承 POSIXct。这消除了错误,但改变了日期时间:

x = data.frame(Index = as.chron(c(15657.00,15657.17)), Var1 = c(1,2), Var2 = c(9,8))
class(x$Index) <- c(class(x$Index),'POSIXct')
y = melt(x,id.vars="Index")

就像我说的,这有点像某处的虫子。我的钱是需要chron将 POSIXct 添加到类向量中,但我可能错了。显而易见的替代方法是使用 POSIXct 日期时间。

于 2013-03-26T16:18:21.733 回答