【问题标题】:Data created from empty data.table causes ggplot error ("replacement has 1 row, data has 0")从空 data.table 创建的数据导致 ggplot 错误(“替换有 1 行,数据有 0”)
【发布时间】:2020-07-15 19:08:43
【问题描述】:

我正在尝试使用 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 不喜欢我的数据是如何生成的。

【问题讨论】:

标签: r ggplot2 data.table


【解决方案1】:

截至data.table 1.12.8data.table not compatible with ggplot when it was generated from empty data.table,这是一个未解决的问题。

原因似乎是从一个空的data.table创建的数据“赋值后没有得到行名。

rownames(DT)
# character(0)

我们可以通过设置 [row names] 属性来手动解决这个问题”:

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)。

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2015-07-01
    • 1970-01-01
    • 2018-05-15
    • 2018-02-28
    相关资源
    最近更新 更多