运行这段代码时
projectile <- data.table()
projectile$angle<- c(15, 30, 45, 60, 75)
projectile$distance <- c(5.1, 8, 10, 8.5, 4.8)
ggplot() + geom_point( aes(projectile$angle, projectile$distance) ) # Works
ggplot(projectile) + geom_point( aes(angle,distance) ) # Does not work
我收到这个错误:
Error in `$<-.data.frame`(x, name, value) :
replacement has 1 row, data has 0
谁能解释一下这个错误的含义、为什么会出现这个错误以及如何解决这个错误?
更新:
如果我使用 data.frame
,在前面的步骤中会出现同样的错误:
projectile <- data.frame()
projectile$angle<- c(15, 30, 45, 60, 75)
错误:
Error in `$<-.data.frame`(`*tmp*`, angle, value = c(15, 30, 45, 60, 75 :
replacement has 5 rows, data has 0
我不立即创建 data.frame(angle=c(..), distance=c(..)
的原因显然是这些值在用户输入之前是未知的稍后。
最佳答案
这可能与数据集的创建方式有关。如果我们将它重新转换为 data.table
,它就可以工作了
ggplot(setDT(setDF(projectile))) +
geom_point( aes(angle,distance) )
data.table
创建为 NULL
对象,然后分配了列。相反,它可以做到
projectile <- data.table(angle = c(15, 30, 45, 60, 75) , distance = c(5.1, 8, 10, 8.5, 4.8))
因为我们在 NULL 对象上赋值,row.names
的属性长度为 0
row.names = integer(0)
当我们以适当的方式构建数据集时,它会显示
row.names = c(NA, -5L)
在dput
输出中
如果我们想从 NULL 对象开始,使用 list
,然后在最后,将其转换为 data.frame
或 data.table
。这样,它将添加 data.frame/data.table 的属性。请注意,data.frame
是一个包含等长元素(即列)的列表
projectile <- list()
projectile$angle<- c(15, 30, 45, 60, 75)
projectile$distance <- c(5.1, 8, 10, 8.5, 4.8)
projectile <- data.frame(projectile)
关于r - 错误 `$<-.data.frame` (x, name, value) : replacement has 1 row, data has 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64164612/