Search code examples
rfor-looprep

A Simple R Loop


I was wondering how to make a simple "loop" to create 21 vertical lines in my plot using "segments()" command?

Specifically, I want the 21 vertical lines to be equally spaced going from 21 consecutive points on the X axis all to 1 on the Y axis. So, for example for the "first vertical line" and the "last "vertical line" the R code is:

m<- seq(0,1,by=.05)
segments(c(0,1),c(0,0),c(0,1),c(1,1),col="red")

Solution

  • You have the word "loop" in quotation marks; I assume that a plain segments() command rather than a true for loop is what you're looking for.

    m = seq(0, 1, length.out=21)    # make 21 equally spaced numbers between 0 and 1
    plot.new()                      # make a new plot device (delete if using an existing plot)
    segments(m, 0, m, 1, col="red") # draw the red line segments
    

    That should make 21 vertical lines.