如何使用嵌套列表存储多个 for 循环?

How to store multiple for loops with nested lists?

我正在尝试存储嵌套的 for 循环结果,但我发现很难这样做。这是我的:

library("pageviews")

lang = c("it.wikipedia", "de.wikipedia", "fr.wikipedia", "es.wikipedia")
bm = c("ECB","Christine Lagarde")

x = list(list()) # store results

for (i in 1:length(lang)) {
  for (j in 1:length(bm)) {

  x[[i]][[j]] = article_pageviews(project = lang[i], article = bm[j], platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily") 

  }
}

x = do.call(rbind, x) # from list to df

我想做的是 运行 每个 langarticle 的代码并相应地存储它。所以我会有一个列表,其中 it.wikipedia 代表欧洲央行,it.wikipedia 代表拉加德,等等......

谁能帮我做一下?

谢谢!

是的,您需要一个嵌套循环。一种方法是使用 purrr.

中的 map_df
library(purrr)
map_df(lang, function(x) map_df(bm, function(y) 
       article_pageviews(project = x, article = y, platform = "all", user_type = "user", 
       start = "2015100100", end = today(), reformat = TRUE, granularity = "daily"))) -> result

所以,你的做法是正确的。但是你忘记了一些事情;你想为每种语言存储两篇文章。

因此你需要 4 个列表,这样,

x <- list(
    list(),
    list(),
    list(),
    list()
    )

由于您的列表是嵌套的,因此您需要使用 purrr::flatten() 撤消此操作,这样,

x <- do.call(rbind, purrr::flatten(x)) # from list to df

在你的for-loop

之后

如果您无法通过嵌套 for 循环创建嵌套 list,也许下面的代码示例可以帮助您

a <- letters[1:5]
b <- LETTERS[1:5]

x <- c()
for (i in seq_along(a)) {
  u <- c()
  for (j in seq_along(b)) {
    u <- c(u, list(paste0(a[i], "-", b[j])))
  }
  x <- c(x, list(u))
}

其中 ux 用于收集不同层的列表,例如

> x
[[1]]
[[1]][[1]]
[1] "a-A"

[[1]][[2]]
[1] "a-B"

[[1]][[3]]
[1] "a-C"

[[1]][[4]]
[1] "a-D"

[[1]][[5]]
[1] "a-E"


[[2]]
[[2]][[1]]
[1] "b-A"

[[2]][[2]]
[1] "b-B"

[[2]][[3]]
[1] "b-C"

[[2]][[4]]
[1] "b-D"

[[2]][[5]]
[1] "b-E"


[[3]]
[[3]][[1]]
[1] "c-A"

[[3]][[2]]
[1] "c-B"

[[3]][[3]]
[1] "c-C"

[[3]][[4]]
[1] "c-D"

[[3]][[5]]
[1] "c-E"


[[4]]
[[4]][[1]]
[1] "d-A"

[[4]][[2]]
[1] "d-B"

[[4]][[3]]
[1] "d-C"

[[4]][[4]]
[1] "d-D"

[[4]][[5]]
[1] "d-E"


[[5]]
[[5]][[1]]
[1] "e-A"

[[5]][[2]]
[1] "e-B"

[[5]][[3]]
[1] "e-C"

[[5]][[4]]
[1] "e-D"

[[5]][[5]]
[1] "e-E"