我想在R中矢量化列表的创建,但只能通过嵌套的for循环获得我想要的东西。为了重现性,我已经包含了一个非常简化的问题版本。有人可以帮我修改或替换我的mapply函数吗?
所需功能:
my_list <- list()
A <- c("one", "two", "three", "four")
B <- c("left", "right")
for (a in A) {
for (b in B) {
my_list <- c(my_list, paste(a, b))
}
}
print(my_list)
输出(为简洁而编辑的空白区域):
[[1]] [1] "one left"
[[2]] [1] "one right"
[[3]] [1] "two left"
[[4]] [1] "two right"
[[5]] [1] "three left"
[[6]] [1] "three right"
[[7]] [1] "four left"
[[8]] [1] "four right"
我尝试对此进行矢量化:
combinate <- function(a, b) {
return(paste(a, b))
}
mapply(combinate, a=A, b=B, SIMPLIFY=FALSE)
输出:
$one [1] "one left"
$two [1] "two right"
$three [1] "three left"
$four [1] "four right"
我不关心标签;我担心从两个列表中循环获得所有八个结果。通过配对两个列表中的第一个项目,然后是两个列表中的第二个项目等,重复更短的列表,我找到了mapply正在完成它应该做的文档。但经过多次搜索后,我无法找到必须存在的内容,这是一种将所有列表项组合在一起的方法,就像嵌套for循环一样。
答案 0 :(得分:3)
我们可以使用expand.grid
和paste
v1 <- do.call(paste, expand.grid(A, B))
或outer
v1 <- c(outer(A, B, paste))
如果这些需要在list
as.list(v1)
检查OP的输出
identical(as.list( c(t(outer(A, B, paste)))), my_list)
#[1] TRUE