R - 重塑 - 熔体错误

时间:2013-01-06 19:37:16

标签: r reshape melt

我正在尝试融化数据框,我得到了这个奇怪的错误。有什么想法吗?

str(zx7)
'data.frame':   519 obs. of  5 variables:
 $ calday.new: Date, format: "2011-01-03" "2011-01-04" "2011-01-05" "2011-01-06" ...
 $ A20    : Time-Series  from 1 to 519: 0 0 0 0 0 0 0 0 0 0 ...
 $ B20    : Time-Series  from 1 to 519: 0 0 0 0 0 0 0 0 0 0 ...
 $ C20    : Time-Series  from 1 to 519: 0 0 0 0 0 0 0 0 0 0 ...
 $ D20    : Time-Series  from 1 to 519: 0 0 0 0 0 0 0 0 0 0 ...

zx7.melt <- melt(zx7, id=c("calday.new"))
Error in `[<-.ts`(`*tmp*`, ri, value = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  : only replacement of elements is allowed

1 个答案:

答案 0 :(得分:2)

问题是旧的“reshape”包的melt()函数在遇到类ts的对象时不知道该怎么做。

所以,你有两个明显的选择(尽管可能还有更多):

  1. unclass在您ts数据之前当前被归类为melt()的变量:

    zx7b <- zx7         # Make a backup, just in case
    library(reshape)    # Notice this is "reshape", not "reshape2"
    head(melt(zx7b, id=c("calday.new"))) # Doesn't work
    # Error in `[<-.ts`(`*tmp*`, ri, value = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  : 
    #   only replacement of elements is allowed
    
    ## Unclass the relevant columns from your data.frame
    zx7b[sapply(zx7b, is.ts)] <- lapply(zx7b[sapply(zx7b, is.ts)],
                                        unclass)
    head(melt(zx7b, id=c("calday.new")))
    #   calday.new variable value
    # 1 2011-01-03      A20     0
    # 2 2011-01-04      A20     0
    # 3 2011-01-05      A20     0
    # 4 2011-01-06      A20     0
    # 5 2011-01-07      A20     0
    # 6 2011-01-08      A20     0
    
  2. 改为升级为“reshape2”,不需要取消分类。

    library(reshape2) # Notice that this is reshape2!
    head(melt(zx7, id=c("calday.new"))) # Melt the original data.frame
    #   calday.new variable value
    # 1 2011-01-03      A20     0
    # 2 2011-01-04      A20     0
    # 3 2011-01-05      A20     0
    # 4 2011-01-06      A20     0
    # 5 2011-01-07      A20     0
    # 6 2011-01-08      A20     0
    
  3. 我没有花时间去做,但你可以从“reshape”软件包的每个版本检查melt.data.frame melt()方法的代码,看看差异在哪里。安装两个软件包,然后键入reshape2:::melt.data.framereshape:::melt.data.frame以查看基础功能。