1

将 dcast 与子集参数一起使用时,当原始数据帧上的 dcast 和子集数据帧上的 dcast 在行中不匹配时,我会收到以下错误。

data.frame(..., check.names = FALSE) 中的错误:参数暗示不同的行数:2、3

我已经用 mtcars 数据集重现了这个错误。下面是带有复制的代码。

 library(reshape2)

 # dataframe
 mtcars2 <- mtcars[, c('vs','am','gear','carb')]
 mtcars2$cars <- row.names(mtcars)
 row.names(mtcars2) <- NULL
 mtcars2$dummyvariable <- 1

 mtcars2.melt <- melt(mtcars2, id=c('cars','vs','am','gear','carb'))

 colnames(mtcars2.melt)
 # [1] "cars"     "vs"       "am"       "gear"     "carb"     "variable" "value"   

 dcast(mtcars2.melt, vs ~ am, drop=FALSE, margins=TRUE)
 # Aggregation function missing: defaulting to length
 #     vs  0  1 (all)
 # 1     0 12  6    18
 # 2     1  7  7    14
 # 3 (all) 19 13    32

 cadillac <- subset(mtcars2.melt, regexpr('Cadillac',cars)>0)
 dcast(cadillac, vs ~ am, drop=FALSE, margins=TRUE)
 # Error in data.frame(..., check.names = FALSE) : 
 #  arguments imply differing number of rows: 2, 3

 dcast(cadillac, vs ~ am, margins=TRUE)
 #      vs 0 (all)
 # 1     0 1     1
 # 2 (all) 1     1

最后一个 dcast 表明可以通过跳过 drop=FALSE 条件来避免错误,但我想要的输出是

    vs 0  1 (all)
1     0 1  0   1
2     1 0  0   0
3 (all) 1  0   1

任何帮助都会很棒!:)

谢谢

4

1 回答 1

0

有趣的问题!我过去曾尝试过,但无法解决。基本上,我试图使用 dcast 导出一系列数据帧(到 csv),无论它们如何被子集化,它们都将具有相同的维度。然后,这将允许我在 Excel 或 Powerpoint 中干净地“加入”它们。

运行上面编辑的代码后,尝试新的 dcast 仍然给我一个错误。

> dcast(mtcars2.melt, vs ~ am, drop=FALSE, margins=TRUE, subset=.(regexpr('Cadillac',cars)>0))
Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 2, 3

and looking at my Session

> sessionInfo()
R version 2.12.2 (2011-02-25)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] plyr_1.4     reshape2_1.1

loaded via a namespace (and not attached):
[1] stringr_0.4  tools_2.12.2

----

使用 DROP=F 和 MARGINS=T 时会发生错误。问题的具体原因似乎是在 dcast 中尝试 cbind(res$labels[[1]], data) 时。在 dcast 中添加一些打印语句可以显示发生了什么:

print("printing data")
print(data)
print("printing res$labels[[1]]")
print(res$labels[[1]])
print("trying cbind(res$labels[[1]], data)")


[1] "printing data"
   0 (all) NA
1  1    NA  1
2 NA    NA NA
3  1    NA  1
[1] "printing res$labels[[1]]"
     vs
1     0
2 (all)
[1] "trying cbind(res$labels[[1]], data)"
Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 2, 3
于 2011-03-16T23:01:27.550 回答