I need to write loops where each iteration has a unique set of variable values. It is not a nested loop "for each i do (for each j do)" type problem. Below is just an example problem, what the loop is doing is not important, it is being able to use multiple variables for each iteration for the loop.
simple loop:
df <- data.frame(num = 1:5)
lookup <- data.frame(colors = c("red", "green", "blue"),
pets = c("cat", "dog", "rabbit"),
stringsAsFactors = FALSE)
for (color in lookup$colors) {
df[, color] <- 1
}
what I want to do (pseudo code):
for (color, pet in lookup$colors, lookup$pets) {
df[, color] <- pet
}
The best approach I have come up with is below, but the additional r[" "] makes the code harder to read:
for (i in 1:nrow(lookup)) {
r <- unlist(lookup[i, ])
df[, r["colors"]] <- r["pets"]
}
df
num red green blue
1 1 cat dog rabbit
2 2 cat dog rabbit
3 3 cat dog rabbit
4 4 cat dog rabbit
5 5 cat dog rabbit
I would like to know what the best generalisable approach to this kind of problem is. In many cases, you could replace the loop with a function to be called for each set of variables, but functions aren't suitable in certain cases.
df[lookup$colors] <- lookup$pets[col(df[lookup$colors])]this?myfunc <- function(color, pet) { do something with vars }and then call it mutiple times for different sets of vars e.g.myfunc("red", "dog"); myfunc("blue", "cat")etc. I would like to be able to do a similar thing but for loops, where functions can't always be used.