Reputation: 2367
When running this code
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
I get this error:
Error in `$<-.data.frame`(x, name, value) :
replacement has 1 row, data has 0
Can anyone explain what this error means, why I have it and how to fix it, please?
UPDATE:
the same error occurs at earlier step if I use data.frame
:
projectile <- data.frame()
projectile$angle<- c(15, 30, 45, 60, 75)
Error:
Error in `$<-.data.frame`(`*tmp*`, angle, value = c(15, 30, 45, 60, 75 :
replacement has 5 rows, data has 0
The reason why I dont create data.frame(angle=c(..), distance=c(..)
right away is obviously that these values are NOT known until the user enters them later.
Upvotes: 4
Views: 2953
Reputation: 887741
It could be related to the way the dataset was created. If we reconvert it to data.table
, it would work
ggplot(setDT(setDF(projectile))) +
geom_point( aes(angle,distance) )
The data.table
was created as a NULL
object and then assigned columns. Instead, it can be done
projectile <- data.table(angle = c(15, 30, 45, 60, 75) , distance = c(5.1, 8, 10, 8.5, 4.8))
As we are assigning on a NULL object, the attributes for row.names
are of length 0
row.names = integer(0)
When we construct the dataset in a proper way, it would show
row.names = c(NA, -5L)
in the dput
output
If we want to start with a NULL object, use a list
, then at the end, convert it to data.frame
or data.table
. In that way, it will add the attributes for data.frame/data.table. Note that data.frame
is a list
with elements (i.e. columns) of equal length
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)
Upvotes: 2
Reputation: 39613
Try this:
#Empty data table
projectile <- data.table()
#Add variables
projectile <- projectile[,list(angle=c(15, 30, 45, 60, 75),
distance=c(5.1, 8, 10, 8.5, 4.8)),]
#Plot
ggplot(plotdat) + geom_point( aes(angle,distance) )
Output:
Upvotes: 1