Reputation: 1885
I was just messing around too long with this, but I cant see what I'm doing wrong. Can someone please give me a hint?
I have a list of filenames. Those names are given to a function which should open the files (spss-files) and return a list of data.frames.
list_of_df <- list()
does_something <- function(...)
items = list(...)
for (item in items){
# open spss-file as data.frame
# ...
df <- data.frame(var1 = "test")
# put dataframe in 'list_of_df'
list_of_df <- append(list_of_df, df)
}
return(list_of_df)
}
filenames <- c("file1.sav", "file2.sav", "file3.sav")
for(filename in filenames){
df_output <- does_something(filename)
}
df_output # Should be a list with three data.frames
Thanks in advance!
Upvotes: 0
Views: 30
Reputation: 538
A few wee edits that will hopefully point you in the right direction:
library(haven) # for loading .sav files
loadSPSSFiles <- function(fileNames){
# Initialise a list to store the dataframes
items <- list()
# Load each file and store
for(fileName in fileNames){
items[[fileName]] <- read_sav(fileName)
}
return(items)
}
fileNames <- c("file1.sav", "file2.sav", "file3.sav")
spssData <- loadSPSSFiles(fileNames)
An edit to reflect @RaphaelS's comment above about using lapply
:
library(haven) # for loading .sav files
fileNames <- c("file1.sav", "file2.sav", "file3.sav")
spssData <- lapply(fileNames, FUN=read_sav)
Upvotes: 2