2017-09-29 34 views
3

我想完成以下任务,而不必输入for循环,而是在单个apply()命令中输入。将一个列表粘贴到一个矢量,重复每个矢量级别的列表

我有一个列表a,我想重复N次,其中N是矢量b的长度,a每次重复粘贴到的b的元件。

到目前为止,我已经做了以下MWE:

var <- paste("var", 1:4, sep="") 
treat <- c("A","B") 
spec <- paste("sp", 1:3, sep="") 
a <- combn(var, 2, simplify = FALSE)#this 6 times, for each treatment and species 
b <- do.call(paste, c(expand.grid(treat, spec), sep='.')) 
a1 <- lapply(a, paste, b[1], sep='.') 
a2 <- lapply(a, paste, b[2], sep='.') 
a3 <- lapply(a, paste, b[3], sep='.') 
a4 <- lapply(a, paste, b[4], sep='.') 
a5 <- lapply(a, paste, b[5], sep='.') 
a6 <- lapply(a, paste, b[6], sep='.') 
a.final <- c(a1,a2,a3,a4,a5,a6) 
a.final 

这将是最佳的,如果我能a之前粘贴b

请注意,我的出发点是3个向量:var,treatspec,所以请随时更改此处的任何内容。

回答

4

选项1:我们可以在没有任何apply()循环的情况下完成此操作。我们unlist()a列表,paste()它复制到b值,然后relist()它基于复制a列表。试试这个:

aa <- relist(
    paste(unlist(a), rep(b, each=sum(lengths(a))), sep="."), 
    rep.int(a, length(b)) 
) 

检查:

identical(aa, a.final) 
# [1] TRUE 

选项1 ba现在,把b值出门前,只要将参数在paste()电话:

relist(
    paste(rep(b, each=sum(lengths(a))), unlist(a), sep = "."), 
    rep.int(a, length(b)) 
) 

选项2:此选项使用apply()循环。这里我们用Map()来做一对一的粘贴。

ra <- rep(a, length(b)) 
aa2 <- Map(paste, ra, relist(rep(b, each=sum(lengths(a))), ra), sep = ".") 

检查:

identical(aa2, a.final) 
# [1] TRUE 

选项2 ba只是交换传递给paste()无名Map()参数。

ra <- rep(a, length(b)) 
Map(paste, relist(rep(b, each=sum(lengths(a))), ra), ra, sep = ".") 
+0

就是这样!非常感谢 – DaniCee

1

力求贴近OP的方法,这可以用嵌套lapply()使用匿名函数来解决:

unlist(lapply(b, function(x) lapply(a, function(y) paste(x, y, sep = "."))), 
     recursive = FALSE) 
[[1]] 
[1] "A.sp1.var1" "A.sp1.var2" 

[[2]] 
[1] "A.sp1.var1" "A.sp1.var3" 

[[3]] 
[1] "A.sp1.var1" "A.sp1.var4" 

... 

[[34]] 
[1] "B.sp3.var2" "B.sp3.var3" 

[[35]] 
[1] "B.sp3.var2" "B.sp3.var4" 

[[36]] 
[1] "B.sp3.var3" "B.sp3.var4" 

注意,b中的a前面粘贴。需要unlist()才能列出顶级列表。

要(在baa.final比较)验证方式工作:

identical(a.final, 
      unlist(lapply(b, function(x) lapply(a, function(y) paste(y, x, sep = "."))), 
       recursive = FALSE)) 
[1] TRUE 
1

这是从头开始创建标签,并返回他们完全不同的方法在36行×2列data.table中,而不是具有长度为2的36个向量的列表:

library(data.table) 
# cross join of treat, spec, var. Note, full labels will be created in sprintf() below 
DT <- CJ(LETTERS[1:2], 1:3, 1:4) 
# non equi join as replacement of combn() 
DT[DT, on = .(V1, V2, V3 > V3), nomatch = 0L, 
    # create labels 
    .(sprintf("%s.sp%s.var%i", V1, V2, V3), 
    sprintf("%s.sp%s.var%i", V1, V2, x.V3))] 
  V1   V2 
1: A.sp1.var1 A.sp1.var2 
2: A.sp1.var1 A.sp1.var3 
3: A.sp1.var1 A.sp1.var4 
4: A.sp1.var2 A.sp1.var3 
5: A.sp1.var2 A.sp1.var4 
6: A.sp1.var3 A.sp1.var4 
7: A.sp2.var1 A.sp2.var2 
... 
29: B.sp2.var2 B.sp2.var4 
30: B.sp2.var3 B.sp2.var4 
31: B.sp3.var1 B.sp3.var2 
32: B.sp3.var1 B.sp3.var3 
33: B.sp3.var1 B.sp3.var4 
34: B.sp3.var2 B.sp3.var3 
35: B.sp3.var2 B.sp3.var4 
36: B.sp3.var3 B.sp3.var4 
      V1   V2 
相关问题