在reshape2中使用melt()的尺寸不匹配

时间:2016-04-06 20:26:15

标签: r dataframe reshape reshape2 melt

我正在尝试融合来自“广泛”的数据框架。格式为' long' R中的格式,使用函数' melt'在包裹' reshape2'。但是,在尝试查看输出数据框时,我遇到了尺寸问题,我无法解密。这是一个例子:

# load reshape2 package
require(reshape2)

# sample data frame generated using dput
df <- structure(list(year = c(2001, 2002, 2003, 2004), 
                     aet = structure(c(493.1, 407.1, 476.7, 501.6), .Dim = 4L), 
                     drainage = structure(c(5.4, 5.4, 5.4, 5.4), .Dim = 4L), 
                     srunoff = structure(c(25.6, 24.3, 56.0, 50.3), .Dim = 4L)),
                .Names = c("year", "aet", "drainage", "srunoff"), row.names = c(NA, 4L), class = "data.frame")

# if i melt without specifying id.vars, it provides a warning but works works fine
df.melt <- melt(df)

# check output
head(df.melt)

# view output
View(df.melt)
# this works fine, and the data frame is visible in RStudio

# now, melt while supplying year as an id variable
df.melt.id <- melt(df, id.vars="year")

# check output
head(df.melt.id)
# the first 6 lines of output print to the console menu, as normal

# view output
View(df.melt.id)

但是,当我尝试查看df.melt.id数据框时,出现以下错误:

Error in FUN(X[[i]], ...) : 
  dims [product 4] do not match the length of object [12]

4对应于数据帧的原始长度,12表示它应该是多长。如果我使用dim(df.melt.id)检查尺寸,则会返回相应的尺寸:[1] 12 3

关于这里发生了什么的任何想法?我试过重新安装reshape2,这没有帮助...

1 个答案:

答案 0 :(得分:2)

当您执行此操作时,它适用于reshape2

df.melt.id <- as.data.frame.array(melt(df, id="year"))