Вопрос

I have been learning a bit of lapply magic in R, but have not figured out how to replace nested loops -- is this also possible?

Here's my problem, and the nested-loop solution.

monCode <- c('F', 'G', 'H', 'J', 'K', 'M', 'N', 
        'Q', 'U', 'V', 'X', 'Z')
yearRange <- as.character(3:15)
yearRange[as.numeric(yearRange) < 10] <- as.character(paste0("0", yearRange[as.numeric(yearRange) < 10]))

outList <- vector()
for(Yr in yearRange) {
    for (mon in monCode) {
        outList <- c(outList, (paste0("IB", mon, Yr, " Comdty")))
    }
}

How would i do this using nested lapply functions, rather than nested loops?

thanks in advance

Это было полезно?

Решение

No need for nested loops or nested lapply.

Use expand.grid to create all your combinations of monCode and yearRange then do.call(sprintf,...) to concatenate them

f <- expand.grid(monCode,yearRange)
outList <- do.call(sprintf, c(f, fmt = 'IB%s%s comdty'))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top