In addition to @joran's answer using the base plot
function with a for
loop, you can also use base plot
with lapply
:
plot(0,0,xlim = c(-10,10),ylim = c(-10,10),type = "n")
cl <- rainbow(5)
invisible(lapply(1:5, function(i) lines(-10:10,runif(21,-10,10),col = cl[i],type = 'b')))
invisible
function simply serves to prevent lapply
from producing a list output in your console (since all we want is the recursion provided by the function, not a list).As you can see, it produces the exact same result as using the for
loop approach.
So why use lapply
?
Though lapply
has been shown to perform faster/better than for
in R (e.g., see here; though see here for an instance where it's not), in this case it performs roughly about the same:
Upping the number of lines to 50000 for both the lapply
and for
approaches took my system 46.3
and 46.55
seconds, respectively.
lapply
was just slightly faster, it was negligibly so. This speed difference might come in handy with larger/more complex graphing, but let's be honest, 50000 lines is probably a pretty good ceiling... So the answer to "why lapply
?": it's simply an alternative approach that works equally as well. :)