【问题标题】:melt with chron与时间融为一体
【发布时间】:2013-03-16 12:17:32
【问题描述】:

我正在尝试使用 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 类)

【问题讨论】:

  • 为什么不简单地创建没有as.chron 的data.frame 然后执行:transform(melt(x, "Index"), Index = as.chron(Index))?
  • 我在尝试重建您的 data.frame 时收到 Error in strptime(x, format, tz = tz) : invalid 'x' argument。
  • @Ista,我已经修复了输入数据中的错误。再试一次。
  • 您的解决方案有什么问题? Maube 我想念一些东西,但你在最终结果中保留了 chron 类。
  • 问题是我想减少计算量

标签: r reshape reshape2 melt chron


【解决方案1】:

(1) 我假设您在运行所示代码之前发出了这个命令:

library(reshape2)

在这种情况下,您可以改用 reshape 包。它不会导致这个问题:

library(reshape)

其他解决方案是

(2)使用R的reshape函数:

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

(3) 或者将 chron 列转换为数字,使用 reshape2 包中的melt 然后再转换回来:

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

添加了其他解决方案。

【讨论】:

  • 是的,我正在使用 reshape2(和依赖于它的 ggplot2)。您的解决方案实用且有效……但需要很多时间(大约 10 倍)
  • 谢谢,第二种解决方案符合我的目的。第三个解决方案简短更正:numeric 到 as.numeric,否则错误消息 argument 'length' incorrect
【解决方案2】:

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

在reshape2中构造melt.data.frame中的数据框时出现问题,这通常使用回收,但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 日期时间。

【讨论】:

  • 确实,它没有给出错误消息,但没有修复它。日期已更改:(11/13/12 00:00:00) -> "1970-01-01 05:20:57 CET"
  • 如果您接受数据帧具有回收某些类而不是其他类的奇怪行为这一事实,那么问题在于 reshape2 以假设其他情况。看我的回答:stackoverflow.com/questions/15641538/melt-with-chron/…
  • @fRed 所以也许最方便的做法是使用 POSIXct 日期时间,而不是 chron?
  • 这可能会引入无法影响 chron 的潜在时区错误。
  • @G.Grothendieck 所以我们回过头来说这是 reshape2 中的一个错误?
猜你喜欢
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 2020-08-23
  • 2013-04-23
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多