I want to code a ggplot2
visualization as a function, and then apply
the function on each row of a dataframe (I want to use apply
to avoid a for
loop, as suggested here.)
The data:
library(ggplot2)
point1 <- c(1,2)
point2 <- c(2,2)
points <-as.data.frame(rbind(point1,point2))
I saved points
as a data frame and it runs fine in ggplot2
:
ggplot(data = points) +
geom_point(aes(x = points[, 1], y = points[, 2])) +
xlim(-3, 3) +
ylim(-3, 3) +
theme_bw()
That's not really the plot I want though: I would like two plots, each one with one point.
Now I build a function that will loop through the rows of the data frame:
plot_data <- function(data) {
ggplot(data) +
geom_point(aes(x = data[, 1], y = data[, 2])) +
xlim(-3, 3) +
ylim(-3, 3) +
theme_bw()
}
I create a list to store the plots:
myplots <- list()
And here is the call to apply
, following this suggestion:
myplots <- apply(points, 1, plot_data)
But I get the following error:
#> Error: `data` must be a data frame, or other object coercible by `fortify()`,
not a numeric vector
But my data are a data frame.
Is this because: "apply()
will try to convert the data.frame into a matrix (see the help docs). If it does not gracefully convert due to mixed data types, I'm not quite sure what would result" as noted in a comment to the answer I referred to?
Still, if I check the data class after the call to apply, the data are still a dataframe:
class(points)
#> [1] "data.frame"
Created on 2021-04-09 by the reprex package (v0.3.0)