O'Reilly logo

R Data Visualization Cookbook by Atmajitsinh Gohil

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Basic loops in R

If we want to perform an action repeatedly in R, we can utilize the loop functionality.

How to do it…

The following lines of code multiply each element of x and y and store them as a vector z:

x = c(1:10)
y = c(1:10)
for(i in 1:10){
z[i] = x[i]*y[i]
}

How it works…

In the preceding code, a calculation is executed 10 times. R performs any calculation specified within {}. We are instructing R to multiply each element of x (using the x[i] notation) by each element in y and store the result in z.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required