Sample data
set.seed(123)
df <- data.frame(loc.id = rep(c(1:3), each = 4*10),
year = rep(rep(c(1980:1983), each = 10), times = 3),
day = rep(1:10, times = 3*4),
x = sample(123:200, 4*3*10, replace = T),
start = 123,
end = 200)
I want to save the plot of each loc.id for all years in a single page using facet_wrap and each loc.id in separate pages as a pdf. Following
loop does this:
loc.vec <- 1:3
pdf("my.pdf")
for(l in seq_along(loc.vec)){
loc.id <- loc.vec[l]
df.sub <- df[df$loc.id == loc.id,]
pp <- ggplot(df.sub,aes(x = day, y = x)) + geom_line() +
facet_wrap(~year) +
geom_vline(aes(xintercept = df.sub$start)) +
geom_vline(aes(xintercept = df.sub$end))
print(pp)
}
dev.off()
Can I achieve without the loop?
Thanks
loc.idI have is way too many. So was wondering if there is any quicker solution to this. Don't mind using a loopforis as good as any from a functional viewpoint. You may get a range of answers suggesting to usemaporapplyorbyor any of the many other ways of looping in R. But none of them changes the underying fact that you need to repeat an operation several times iterating over loc.id. In other words you need a loop and you already have one that works just fine.loc.id, would this loop will still be faster compared to the solution below.