Scripting Loops exercises Vol.2
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
[For this exercise, first write down your answer, without using R. Then, check your answer using R.]
Answers to the exercises are available here.
Exercise 1
Using the following variables:
x=1
i=c(1:10)
For this exercise, write a for() loop that increments x by two for each i.
Exercise 2
Using the following variables:
x=1
y=40
i=c(1:10)
For this exercise, write a for() loop that increments x by three and decrease y by two, for each i.
Exercise 3 Exercise 4 Exercise 5 Using the following variable: Exercise 6 Using the following variable: Exercise 7 Using the following variable: Exercise 8 Using the following variable: Exercise 9 Using the following variable: Exercise 10 Using the following variable: For this exercise, type a for() loop that calculate Want to practice loops a bit more? We have more exercise sets on this topic here.
Using the following variables:
a,b
For this exercise, write a nested for() loop (where the outer for loop increment a from 2 to 8 by 1, and the
inner for loop increment b from 1 to 6 by 1) that print “a, ‘ less than ‘,b” if a
Using the following variable:
x=c(2,4)
For this exercise, type a while () loop that adds even numbers to x, while the length of x is less than 12.
For example, in the first iteration you get x = 2,4,6
, and the third x =2,4,6,8
.
a=15:10
b=20:15
For this exercise, type a while () loop that computes a vector x=225 224 221 216 209 200
,such that
x[1]=a[1]*b[6]
x[2]=a[2]*b[5]
x[3]=a[3]*b[5]
.
.
x[6]=a[6]*b[1]
a=1:10
For this exercise, type a while () loop that computes a vector x=1 3 6 10 15 21 28 36 45 55
,such that
x[1]=a[1]
x[2]=a[1]+a[2]
x[3]=a[1]+a[2]+a[3]
.
.
i=10
x=10
For this exercise, type a repeat () loop that decreasing i computes x=x/i
until i=0
.
x=100
y=50
i=1
For this exercise, type a repeat () loop that incrementing i computes x=x-i and y=y+i
until x<y
.
x=as.Date("10/11/2017","%d/%m/%Y")
For this exercise, type a repeat () loop that increment x until x is equal to 31/12/2017.
x=cbind(c(1,2,3,4,9,7,4,3),c(3,1,2,5,3,6,5,3))
y=3 8 18 44 126 140 100 84
, such that
y[1]=x[1,1]*x[1,2]
y[2]=x[2,1]*sum(x[1:2,2])
y[3]=x[3,1]*sum(x[1:3,2])
.
.
.
y[8]=x[8,1]*sum(x[1:8,2])
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.