How to Loop Through a List in 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

5

1 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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest