本文介绍了R-重塑-熔化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试融化一个数据框,但我收到了这个奇怪的错误。知道为什么吗?
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
推荐答案
问题是旧的"重塑"包的melt()
函数在遇到类ts
的对象时不知道该怎么办。
因此,您有两个明显的选择(尽管可能还有更多):
unclass
您之前melt()
当前分类为ts
的变量: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
改为升级到"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
我没有花时间来做这件事,但是您可以检查melt()
的melt.data.frame
方法的代码,看看不同之处在哪里。安装这两个程序包,然后键入reshape2:::melt.data.frame
和reshape:::melt.data.frame
以查看基础函数。
这篇关于R-重塑-熔化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!