在多个列表上使用非嵌套循环的意外行为

时间:2014-06-18 04:13:30

标签: r for-loop vectorization

我想制作一堆像

这样的字符向量
[1] "w2q5ea" "w2q5eb" "w2q5ec" "w2q5ed"

我有以下设置:

vars <- list(
  w1 = c("w2q5e*","w2q7e*"),
  w2 = c("w3q9*5","w3q13*5","w3q15*5"),
  w3 = c("w4q17*c","w4q16*c","w4q15*c"),
  w4 = c("w5q16*c","w5q14*c","w5q11*c"),
  w5 = c("w5q8*c"))

alphabet <- function(n) lapply(n,function(N) letters[1:N])

nletts <- list(
  w1 = list(unlist(alphabet(10)),unlist(alphabet(10))),
  w2 = list(unlist(alphabet(10)),unlist(alphabet(10)),unlist(alphabet(10))),
  w3 = list(unlist(alphabet(10)),unlist(alphabet(6)),unlist(alphabet(6))),
  w4 = list(unlist(alphabet(6)),unlist(alphabet(6)),unlist(alphabet(6))),
  w5 = list(unlist(alphabet(6))))

所以,例如,

> nletts[["w1"]]
[[1]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

[[2]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

为了有希望产生类似于

的东西
[1] "w2q5ea" "w2q5eb" "w2q5ec" "w2q5ed"
[1] "w2q7ea" "w2q7eb" "w2q7ec" "w2q7ed"

这就是我想到的以下代码:

temp <- list()
for( i in 1:2 ){
letts <- unlist(nletts[["w1"]][[i]])
for(l in seq_along(nletts)) for( v in vars[["w1"]] ) {
        temp <- append(temp,sub("\\*",letts[l],v))
    }
}

但显然它不对。我没有打印结果是为了让这篇文章有点可读,但你可以运行我所拥有的并亲自看看。由于某种原因,它似乎循环三次而不是一次。我怀疑某个地方的东西是以我错过的方式被矢量化的,而对于我的生活,我无法弄清楚它是什么。我已经一遍又一遍地重写了这段代码大约四个小时,每次都得到完全相同的问题。除了所有理解之外的奇怪之处在于我甚至可以用整数替换l并手动逐步执行以获得正确的结果。

忘记尝试做我原本想做的工作,我可以在三小时前完成复制&amp;糊。我只是想了解出了什么问题。整个事情从一开始就感觉Hacky和Bad,所以欢迎另外的建议。


使用

for( i in seq_along(vars[["w1"]]) ){

    print(sprintf(vars[["w1"]][i],letters[ nletts[["w1"]][i] ] ))

}

但我仍然想知道上面出了什么问题。我认为发生的事情是我真的在nletts的每个列表元素上循环两次。我意识到我的循环是嵌套的,即使我不想要它们,所以也许问题在于某处。同时使用相同的索引可以明确解决问题。


不需要append的更好的解决方案:

whatever <- sapply(1:5, function(w){
    sapply( seq_along(vars[[w]]), function(i){
        sprintf(vars[[w]][i],letters[ 1:nletts[[w]][i] ] )
    },simplify=F)
},simplify=F)

但仍然没有解释出现了什么问题。

1 个答案:

答案 0 :(得分:1)

尝试这个食谱怎么样:

R> vars <- c("w2q5e%s", "w5q8%sc")
R> lapply(vars, function (x) sprintf(x, letters))
[[1]]
 [1] "w2q5ea" "w2q5eb" "w2q5ec" "w2q5ed" "w2q5ee" "w2q5ef" "w2q5eg" "w2q5eh" "w2q5ei"
[10] "w2q5ej" "w2q5ek" "w2q5el" "w2q5em" "w2q5en" "w2q5eo" "w2q5ep" "w2q5eq" "w2q5er"
[19] "w2q5es" "w2q5et" "w2q5eu" "w2q5ev" "w2q5ew" "w2q5ex" "w2q5ey" "w2q5ez"

[[2]]
 [1] "w5q8ac" "w5q8bc" "w5q8cc" "w5q8dc" "w5q8ec" "w5q8fc" "w5q8gc" "w5q8hc" "w5q8ic"
[10] "w5q8jc" "w5q8kc" "w5q8lc" "w5q8mc" "w5q8nc" "w5q8oc" "w5q8pc" "w5q8qc" "w5q8rc"
[19] "w5q8sc" "w5q8tc" "w5q8uc" "w5q8vc" "w5q8wc" "w5q8xc" "w5q8yc" "w5q8zc"