[英]List of recursively concatenated lists in R
Is there a concise way to create a list of recursively concatenated lists in R? 是否有一种简洁的方法来在R中创建递归连接列表的列表?
Here's a concrete illustration of the type of problem I'd like to solve: Given two lists, such as 以下是我想要解决的问题类型的具体说明:给出两个列表,例如
u <- list("A", list("B", list("C", "D")), "E")
v <- c("x", "y")
I would like to (recursively) produce the following list of character vectors 我想(递归地)生成以下字符向量列表
w <- list(c("A", "x"), c("A", "y"),
c("B", "C", "x"), c("B", "C", "y"),
c("B", "D", "x"), c("B", "D", "y"),
c("E", "x"), c("E", "y"))
By “concise” I mean in an R-idiomatic manner with a minimal number of explicit for-loops. “简洁”是指R-idiomatic方式,具有最少数量的显式for循环。
What I've tried : I first tried solving the more basic problem of pairwise concatenation, that is, the problem of forming a list like 我试过的 :我首先尝试解决成对连接的更基本问题,即形成列表之类的问题
r <- list(c("A", "x"), c("A", "y"), c("B", "x"), c("B", "y"),
c("C", "x"), c("C", "y"))
from two lists like 来自两个列表
p <- list("A", "B", "C")
q <- list("x", "y")
However, performing the seemingly sensible operation 但是,执行看似明智的操作
outer(p, q, FUN = "c")
threw the exception 扔了例外
dims [product 6] do not match the length of object [12]
What gives? 是什么赋予了?
One option might be 一种选择可能是
w1 <- do.call(c,lapply(u, function(x) {
x1 <- if(!is.list(x)) outer(x,v, FUN=paste)
else t(outer(do.call(paste, x), v, FUN= paste))
strsplit(x1, " ")}))
identical(w, w1)
#[1] TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.