Carmen
Carmen

Reputation: 793

Looping efficiently over several lists without creating x for loops in R

I am trying to loop simultaneously over several lists. However, I am using several for-loops to reach the desired result. I am wondering if there is a better, more efficient way to do this.

Here's my code

for (i in list(3,6)){
  for (n in list("rmse.","mape.", "mpe.")){
    for (b in list("base.", "rev.")){
      a <- paste0(b, "fcst")
      c <- paste0(n, a)
      x <- paste0(c, i)
      print(x)
    }
  }
}

And here the result:

[1] "rmse.base.fcst3"
[1] "rmse.rev.fcst3"
[1] "mape.base.fcst3"
[1] "mape.rev.fcst3"
[1] "mpe.base.fcst3"
[1] "mpe.rev.fcst3"
[1] "rmse.base.fcst6"
[1] "rmse.rev.fcst6"
[1] "mape.base.fcst6"
[1] "mape.rev.fcst6"
[1] "mpe.base.fcst6"
[1] "mpe.rev.fcst6"

I am pretty sure that there is a more efficient way, maybe with lapply? Storing the results in one list, would be very helpful as well, so any suggestions are more than welcome.

Upvotes: 1

Views: 52

Answers (2)

Varun Rajan
Varun Rajan

Reputation: 276

This will generate a dataframe with the last column x being what you need,

df = expand.grid(i = c(3,6),
             n = c("rmse.", "mape.", "mpe."),
             b = c("base.", "rev.")) %>%
mutate(x = paste0(n, b, "fcst", i))

Just do

df %>% select(x)

to view them. You can store it somewhere as well to refer to it.

Upvotes: 4

Adam Quek
Adam Quek

Reputation: 7153

zz <- expand.grid(n,b,"fcst",i) 
do.call(paste0, zz)

# [1] "rmse.base.fcst3" "mape.base.fcst3" "mpe.base.fcst3"  "rmse.rev.fcst3" 
# [5] "mape.rev.fcst3"  "mpe.rev.fcst3"   "rmse.base.fcst6" "mape.base.fcst6"
# [9] "mpe.base.fcst6"  "rmse.rev.fcst6"  "mape.rev.fcst6"  "mpe.rev.fcst6" 

Input:

n <- c("rmse.","mape.", "mpe.")
b <- c("base.", "rev.")
i <- c(3,6)

Upvotes: 2

Related Questions