I have a loop that's nested inside a larger function (but I've pulled it out since it's the only part malfunctioning). When I run the code through the loop, it loops correctly through the vertical line dataframe, but only plots the third column of the histogram dataframe (code below). However, if I run the exact same code manually, everything works correctly.
Loop code:
plts1 <- list()
for (i in 1:ncol(rep_coefs)) {
plts1[[i]] <- ggplot(rep_coefs, aes(x = rep_coefs[[i]])) +
geom_histogram(bins = 10) +
geom_vline(xintercept = og_coef[[i]], color = "red") +
labs(x = names(rep_coefs)[i])
}
grid.arrange(grobs = plts1, nrow = 1, ncol = ncol(rep_coefs))
Output: plots from loop
Only the third column in rep_coefs gets plotted in the histogram, but it cycles through the og_coef data correctly as a vertical line and the names correctly as the label for the x-axis.
The exact same code, manually looping through the columns.
Manual code:
plts2 <- list()
plts2[[1]] <- ggplot(rep_coefs, aes(x = rep_coefs[[1]])) +
geom_histogram(bins = 10) +
geom_vline(xinterceplts2 = og_coef[[1]], color = "red") +
labs(x = names(rep_coefs)[1])
plts2[[2]]<-ggplot(rep_coefs, aes(x = rep_coefs[[2]])) +
geom_histogram(bins = 10) +
geom_vline(xinterceplts2 = og_coef[[2]], color = "red") +
labs(x = names(rep_coefs)[2])
plts2[[3]]<-ggplot(rep_coefs, aes(x = rep_coefs[[3]])) +
geom_histogram(bins = 10) +
geom_vline(xinterceplts2 = og_coef[[3]], color = "red") +
labs(x = names(rep_coefs)[3])
grid.arrange(grobs = plts2, nrow = 1, ncol = ncol(rep_coefs))
Output: plots made manually
The replication data can be found here: link to data
aes()values are saved as unevaluated expressions. That means thatiisn't evaluated until the plot is drawn, not when it's built. You can inject the current value with some tidyeval syntax: Tryaes(x = rep_coefs[[!!i]])oraes(x=.data[[names(rep_coefs)[i]]])