D. Studer
D. Studer

Reputation: 1875

create objects in a loop and enter it to a function

I have the following r code:

df1 <- haven::read_sav(here::here("data", "filename.sav"))
df2 <- haven::read_sav(here::here("data", "otherfilename.sav"))
df3 <- haven::read_sav(here::here("data", "anotherone.sav"))

result <- stackDf(df1, df2, df3, df4)

which I want to facilitate:

filenames <- c("filename.sav",
         "otherfilename.sav",
         "anotherone.sav")

for (filename in filenames){
  # Don't know what to do here
  file <- haven::read_sav(here::here("data", filename))
}

result <- stackDf(df1, df2, df3, df4)

But I don't know how to get the file-object (within the loop) to the call of my function stackDf(). Can somebody please help me? Yes, there might be more than just three files in reality, because of that I'd rather like to automize it.

Upvotes: 1

Views: 40

Answers (2)

akrun
akrun

Reputation: 887138

We can use map

library(purrr)
out <- map(filename, ~ haven::read_sav(here::here("data", f))) %>%
         reduce(stackDF)

Upvotes: 1

DaveArmstrong
DaveArmstrong

Reputation: 21937

What about:

file <- lapply(filename, 
               function(f) haven::read_sav(here::here("data", f)))
do.call("stackDF", file)

Upvotes: 1

Related Questions