对嵌套循环使用lapply [英] using lapply for nested loops

查看:55
本文介绍了对嵌套循环使用lapply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 R 中学习了一些 lapply 魔术,但是还没有弄清楚如何替换嵌套循环-这也是可能的吗?

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")))
    }
}

我该如何使用嵌套的 lapply 函数而不是嵌套的循环来做到这一点?

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

预先感谢

推荐答案

不需要嵌套循环或嵌套lapply.

No need for nested loops or nested lapply.

使用 expand.grid 创建 monCode yearRange 的所有组合,然后创建 do.call(sprintf,...)将它们串联起来

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'))

这篇关于对嵌套循环使用lapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆