0

我试图融化一个数据框,我得到了这个奇怪的错误。任何想法为什么?

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
4

2 回答 2

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
    

我没有花时间去做,但是你可以检查每个版本的“reshape”包的melt.data.frame方法代码melt(),看看差异在哪里。安装这两个包,然后键入reshape2:::melt.data.framereshape:::melt.data.frame查看底层功能。

于 2013-01-09T08:27:51.950 回答
2

我不知道您是如何创建结构的,但是当我这样做时,它对我有用

zx7 <- data.frame( calday.new=seq(from = as.Date('2011-01-03'),by=1,length.out=519),
                   A20=ts(rep(0,519)),
                   B20=ts(rep(0,519)),
                   C20=ts(rep(0,519)),
                   D20=ts(rep(0,519)))

我创建了与上面相同的结构:

str(zx7)
'data.frame':   519 obs. of  5 variables:
 $ calday.new: Date, format: "2011-01-03" "2011-01-04" "2011-01-05" ...
 $ 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 ...

然后我融化:

head(melt(zx7, 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
于 2013-01-07T07:21:33.400 回答