Stephan
Stephan

Reputation: 2246

r function call with 2 lists of arguments and bind_rows of existing

I want to call a function with 2 lists of arguments and want to rbind (preferred bind_rows) all existing. Thats my generalised code:

combine <- function(arg1, agr2){
  df_gen<-read_csv2(paste0(arg1,"/FolderPref", arg2,"/PID_var.csv")) %>%
  select(PID, Site) %>%
  mutate(Group=arg2)

  dir<-list.files(path = paste0(arg1,"/FolderPref", arg2), pattern = "\\General_information.csv$")
  df<-read_csv2(paste0(arg1,"/FolderPref", arg2,"/", dir)) %>%
    filter(Status == 2) %>%
    inner_join(df_gen, by="PID") %>%
    mutate(enrollment=dmy_hm(Date)) %>%
    select(PID, Group, Site, enrollment) 
  return(df)
}

arg1<-list("center1", "center2", "center3", "center4", "center5")
arg2<-list("Group1", "Group2", "Group3", "Group4", "Group5")

My ultimate aim is to have one df with all possible combinations of arg1 (center1-group1, center1-group2,... center2-group1, center2-group2,... )

The problem is that not all "General_Information.csv" files will be existing. so from 5x5 possible combinations the final data frame will have less than 25 single df's.

Of course i can write 25 lines of "combine" and comment the df's that are not existing in a "bind_rows" call. But I know that there will be a nicer solution to this problem.

Looking forward to your support.

Upvotes: 0

Views: 110

Answers (1)

pogibas
pogibas

Reputation: 28339

This is what I usually do:

# Make all possible combinations of your arguments
argExpand <- expand.grid(arg1, arg2)
head(argExpand)

#     Var1   Var2
# 1 center1 Group1
# 2 center2 Group1
# 3 center3 Group1
# 4 center4 Group1
# 5 center5 Group1
# 6 center1 Group2

# Iterate using foreach
library(foreach)
foreach(i = 1:nrow(argExpand), .combine = rbind) %do% {
   combine(argExpand[i, 1], argExpand[i, 2])
}

PS.: To work with files that might not exist use file.exists():

file <- paste0(arg1,"/FolderPref", arg2,"/PID_var.csv")
if (file.exists(file)) {
    df_gen <- read_csv2(file) %>%
        select(PID, Site) %>%
        mutate(Group = arg2)
}

Upvotes: 1

Related Questions