0

Why do these give different behaviour? If I use the loop I only see the last line but if I unroll the loop I see both.

p <- ggplot(shortdf, aes(datetime))
p <- p + geom_line(aes(y = as.numeric(as.character(shortdf[[1]]))))
p <- p + geom_line(aes(y = as.numeric(as.character(shortdf[[2]]))))

p <- ggplot(shortdf, aes(datetime))
for (i in 1:2) {
    p <- p + geom_line(aes(y = as.numeric(as.character(shortdf[[i]]))))
}
idontgetoutmuch
  • 1,621
  • 11
  • 17
  • Thanks very much but sadly that doesn't work - I see one line being drawn which is quickly replaced by the second line. And also my question remains: surely the semantics of a loop should be its unrolled version? – idontgetoutmuch Sep 29 '21 at 18:36
  • 1
    Please make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Martin Gal Sep 29 '21 at 18:44
  • Maybe https://stackoverflow.com/questions/67320659/adding-layers-in-ggplot2-with-for-loops helps to answer your question. Instead of using a for loop you could do `p + lapply(1:2, function(i) geom_line(aes(y = as.numeric(as.character(shortdf[[i]])))))` – stefan Sep 29 '21 at 18:51
  • That's mad - lol - lapply works - I guess somehow lapply is forcing evaluation - I can't even begin to guess at R's semantics - thank you very much – idontgetoutmuch Sep 29 '21 at 19:03
  • @stefan - I can answer the question with your comment but you may prefer to answer and get the points (I think that's how SO works) – idontgetoutmuch Sep 29 '21 at 19:10

0 Answers0