How to iterate over a list in R
I have a list to say:
dataSet$mixed_bag <- list("Hello", c("USA", "Red", "100"), c("India", "Blue", "76"))
I want to loop over this list and create new variables based on the contents of the list. The pseudocode will 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 I would do this in R
+3
source to share
1 answer
something like that?
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"
+6
source to share