How to apply a function on a particular column in a dataframe?
A for loop allows us to iterate over an object (such as a vector) and we can then perform and execute blocks of codes for every loop we go through. The syntax for a for loop is:
for (temporary_variable in object){
# Execute some code at every loop
}
For loop can be applied in many real world cases when a proper iteration is needed in the data.Iteration can be done in a vector, a list, or a matrix.
In every iteration, we put a temporary variable in the data to pass in a loop and we execute to change the data we need.
To iterate for loop over a vector, we have to define a vector first
vec <- c(1,2,3,4,5)
To iterate, we can use a for loop
for (temp_var in vec){
print(temp_var)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
The output will be just the number passed in the vectors but we can also perform operations like addition or subtraction or other mathematical operations. This can be done by adding function or arguments along with a temporary variable.
Suppose temp_var + 5 will add 5 to every iteration of the data present in the vector. Let us see in R
for (temp_var in vec){
print(temp_var+5)
}
Output
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10