How to iterate a for loop over a list in R?

815    Asked by Uditisingh in Data Science , Asked on Nov 3, 2019
Answered by Uditi singh

To iterate over a list, we have to define a list

li <- list(1,2,3,4,5)

To iterate the list ‘li’

for (temp_var in li){

    print(temp_var)

}

Output

[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

So the loop iterated every element in the passed. Now let us add some operation and see how the loop iterates over such function.

for (temp_var in li){

  print(temp_var*10)

}

Now let us see the output

[1] 10

[1] 20

[1] 30

[1] 40

[1] 50

Here we can see that every element in the list has been multiplied with 10 and iterated.



Your Answer

Interviews

Parent Categories