How to include a for loop to plot?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

How to include a for loop to plot?

Nati
This post has NOT been accepted by the mailing list yet.


I have to do this exercise for an interview on Monday 4: "Write an R script that plots the numbers from 1 to 100 (e.g. along the diagonal of a plot) in black colour. But for multiples of a=2, colour the point in red; and for multiples of b=3, colour the point in blue. For numbers which are multiples of BOTH a and b, colour the point in green. For any black point ONLY (i.e. not for coloured points), print the value of the number beside the point. Try to use at least one for loop, one if statement, and one function in your code." I did the exercise without the required for loop using this script:

x=c(1:100)
plot(x, col= ifelse(x%%6==0, "green", ifelse(x%%3==0, "blue", ifelse(x%%2==0, "red", "black"))), ylim=c(0,100))
x2=x[which(x%%2==0)]
x2
x3=x[which(x%%3==0)]
x3
x6=x[which(x%%6==0)]
x6
X=x[-c(x2,x3,x6)]
X
text(X, X, pos=1)

I am now trying to do it with the loop but since I really don't know R programming language I am really struggling since yesterday. So here I am:

x=c(1:100)
for(i in 1:100)
{
if(i%%6==0)
{plot(x, xlim=c(0,100), ylim=c(0,100), col="green")}
if(i%%3==0)
{plot(x , xlim=c(0,100), ylim=c(0,100),col="blue")}
if(i%%2==0)
{plot(x, xlim=c(0,100), ylim=c(0,100), col="red")}
else {plot(x, xlim=c(0,100), ylim=c(0,100), col="black")}
}

which gives me a diagonal that changes color... nothing to do whith what I expect. Does anyone would be kind enough to help me before Monday ? Thank you very much