嵌套应用多个参数

时间:2019-11-04 11:18:23

标签: r for-loop lapply

我想使用apply系列而不是for循环。

我的for循环是嵌套的,包含几个向量和一个列表,我不确定如何使用apply作为参数输入。

Codes <- c("A","B","C")
Samples <- c("A","A","B","B","B","C")
Samples_Names <- c("A1","A2","B1","B2","B3","C1")
Samples_folder <- c("Alpha","Alpha","Beta","Beta","Beta","Charlie")
Df <- list(data.frame(T1 = c(1,2,3)), data.frame(T1 = c(1,2,3)), data.frame(T1 = c(1,2,3)))


for (i in 1:length(Codes)){

  for (j in 1:length(Samples)) {

    if(Codes[i] == Samples[j]) {

      write_csv(Df[[i]], path = paste0(Working_Directory,Samples_folder[j],"/",Samples_Names[j],".csv"))

    }
  }
}

这将给出Alpha中的A1,A2,Beta中的B1,B2,B3和charlie中的C1的输出。

1 个答案:

答案 0 :(得分:1)

由于您只想使用write_csv,因此我们可以使用pwalk中的purrr在三个相等大小的向量上完成此操作。无需在Codes上包含循环,因为对于应用中的每个迭代,我们可以write_csvSamplesCodes中找到的位置相对应的数据集。

我将Working_Directory缩短为WD

library(purrr)

pwalk(list(Samples, Samples_folder, Samples_Names), 
      function(x, y, z) write_csv(Df[[match(x, Codes)]], path = paste0(WD, y, "/", z, ".csv")))