Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a list in R

Tags:

loops

r

I have a list lets say:

dataSet$mixed_bag <- list("Hello", c("USA", "Red", "100"), c("India", "Blue", "76")) 

I want to iterate through this list and create new variables based on the contents of the list. A pseudo code would look something like this.

foreach row in dataSet$mixed_bag {     if (sapply(dataSet$mixed_bag, length) == 3) {         dataSet$country <- dataSet$mixed_bag[[row]][1];         dataSet$color <- dataSet$mixed_bag[[row]][2];         dataSet$score <- dataSet$mixed_bag[[row]][3];     } else if (sapply(dataSet$mixed_bag, length) == 2) {        #Do something else     } else {        # Do nothing     } } 

Please suggest how would I do this in R

like image 756
user3422637 Avatar asked Oct 10 '14 10:10

user3422637


People also ask

Can we loop through a list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by refering to their indexes. Remember to increase the index by 1 after each iteration.

How do I loop through an array in R?

To iterate over items of a vector in R programming, use R For Loop. For every next iteration, we have access to next element inside the for loop block.


1 Answers

something like this?

dataList <- list("Hello", c("USA", "Red", "100"), c("India", "Blue", "76")) for(i in dataList)   {print(i)} 

returns:

[1] "Hello" [1] "USA" "Red" "100" [1] "India" "Blue"  "76"    

or:

for(i in dataList)   {   for(j in i)   {print(j)}   } 

returns:

[1] "Hello" [1] "USA" [1] "Red" [1] "100" [1] "India" [1] "Blue" [1] "76" 
like image 130
phonixor Avatar answered Oct 02 '22 17:10

phonixor