In this R tutorial, we will take a look into for loops. At a very basic level, a loop will iterate over a sequence under set conditions that must be met. In other, words it can allow the automation of code that calls for repetition.
Vector is a basic data structure in R and contains elements of the same type. The vector data types can include logical, integer, double, character, complex or raw and can be checked with typeof() function. The length property of a vector is important as well and can be checked by using the length() function.
for Loop Syntax
1 2 3 | for (val in sequence) { statement } |
The sequence is a vector and the val will take each value that’s iterated over the loop. With each iteration of the loop, the statement will be evaluated and meet the requirements.
Input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | years <- c(2000,2001,2002,2003,2004,2005,2006,2007) count <- 0 for (year in years) { if(year %% 2 == 0) count = count+1 } print ('Vector Lengths') length(years) length(year) print('Vector Types') typeof(years) typeof(year) print(count) |
Output:
1 2 3 4 5 6 7 8 9 | [1] "Vector Lengths" [1] 8 [1] 1 [1] "Vector Types" [1] "double" [1] "double" [1] 4 |
In the above example, the loop iterates 8 times as the vector years has 8 elements. Within each iteration, year will take on the value of each element in year. The count variable will add 1 to each time a value meets the criteria if being divisible by 2.