我正在尝试融化数据框,我得到了这个奇怪的错误。有什么想法吗?
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
答案 0 :(得分:2)
问题是旧的“reshape”包的melt()
函数在遇到类ts
的对象时不知道该怎么做。
所以,你有两个明显的选择(尽管可能还有更多):
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
改为升级为“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.frame
和reshape:::melt.data.frame
以查看基础功能。