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
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With