R – How to loop through a list in R

loopsr

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

Best Answer

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"