Ali
Ali

Reputation: 1080

Nested apply with multiple parameters

I would like to use the apply family instead of a for loop.

My for loop is nested and contains several vectors and a list, for which I am unsure how to input as parameters with 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"))

    }
  }
}

This will give an output of A1,A2 in Alpha, B1,B2,B3 in Beta, and C1 in charlie.

Upvotes: 0

Views: 47

Answers (1)

caldwellst
caldwellst

Reputation: 5956

Since you are looking to just use write_csv, we can use pwalk from purrr to accomplish this over the three equal size vectors. No need to include the loop on Codes, as for each iteration in the apply we can write_csv the dataset corresponding to where Samples is found in Codes.

I shortened Working_Directory to 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")))

Upvotes: 1

Related Questions