r - 错误 `$<-.data.frame` (x, name, value) : replacement has 1 row, data has 0

标签 r ggplot2 data.table

运行这段代码时

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.framedata.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/

相关文章:

r - 将自定义图像添加到 geom_polygon 填充 ggplot

r - 从 fread 中提取行数而不读取整个文件

javascript - R Leaflet自定义属性字符串

r - 如何按升序对r中数据框的所有列进行排序?

r - 如何在条形图上添加渐变填充?

r - 使用 `by` 过滤 data.table 中的行

r - data.table 删除关键行并汇总

r - 如何使用自定义列名称将数据框转置为 Shiny

r - R 中的函数和 try()

r - 添加阴影效果ggplot2条形图(barplot)