在 reshape2 中使用 melt() 进行维度不匹配
Dimension Mismatch using melt() in reshape2
我正在尝试使用包 'reshape2' 中的函数 'melt' 在 R 中将数据框从 'wide' 格式融化为 'long' 格式。但是,在尝试查看我无法破译的输出数据帧时,我遇到了维度问题。这是一个例子:
# 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)
检查尺寸,它 returns 合适的尺寸:[1] 12 3
对这里发生的事情有什么想法吗?我已经尝试重新安装 reshape2 但没有帮助...
当你这样做时它与 reshape2
一起工作:
df.melt.id <- as.data.frame.array(melt(df, id="year"))
我正在尝试使用包 'reshape2' 中的函数 'melt' 在 R 中将数据框从 'wide' 格式融化为 'long' 格式。但是,在尝试查看我无法破译的输出数据帧时,我遇到了维度问题。这是一个例子:
# 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)
检查尺寸,它 returns 合适的尺寸:[1] 12 3
对这里发生的事情有什么想法吗?我已经尝试重新安装 reshape2 但没有帮助...
当你这样做时它与 reshape2
一起工作:
df.melt.id <- as.data.frame.array(melt(df, id="year"))