r语言 - 从空 data.table 创建的数据会导致 ggplot 错误 ( "replacement has 1 row, data has 0" )



我试图用ggplot绘制线性模型生成的两个连续变量,但我弹出了一个奇怪的错误。

这里有一个可重复的例子:

library(data.table)
library(ggplot2)
set.seed(1)
n <- 4
DT <- data.table()
DT[, x := rnorm(n)]
DT[, z := rep(-.5:+.5, each = n/2)]
DT[, e := rnorm(n, 0.5)]
DT[, y := 1 + 2*x + 3*z + 4*x*z + e]
ggplot(DT, aes(x, y)) + geom_point()

执行时,脚本返回以下错误:

> ggplot(DT, aes(x, y)) + geom_point()
Error in `$<-.data.frame`(x, name, value) : 
replacement has 1 row, data has 0

生成的数据似乎没有任何问题:

> DT
x    z          e          y
1: -0.6264538 -0.5  0.8295078  0.3295078
2:  0.1836433 -0.5 -0.3204684 -0.8204684
3: -0.8356286  0.5  0.9874291  0.1449146
4:  1.5952808  0.5  1.2383247 10.1194479
> str(DT)
Classes ‘data.table’ and 'data.frame':  4 obs. of  4 variables:
$ x: num  -0.626 0.184 -0.836 1.595
$ z: num  -0.5 -0.5 0.5 0.5
$ e: num  0.83 -0.32 0.987 1.238
$ y: num  0.33 -0.82 0.145 10.119
- attr(*, ".internal.selfref")=<externalptr> 

奇怪的是,以下代码工作时没有问题:

DT2 <- data.table(x = rnorm(n), y = rnorm(n))
ggplot(DT2, aes(x, y)) + geom_point()

我不确定问题是什么,但我猜ggplot不喜欢我的数据是如何生成的。

这是data.table 1.12.8:data.table从空data.table生成时与ggplot不兼容的未决问题。

原因似乎是从空的CCD_在赋值后不会得到行名";

rownames(DT)
# character(0)

">我们可以通过设置[行名称]属性来手动解决此问题":

setattr(DT, "row.names", seq.int(n))
rownames(DT) 
# [1] "1" "2" "3" "4"
ggplot(DT, aes(x, y)) + geom_point()
# works!

OP在该问题中建议的另一个解决方案是转换为data.frame(setDF((然后也可能将其转换回data.table(。

相关内容

最新更新