1

I am trying to read all SPSS files in a folder in R to different data.frames. I only need that, all of those files read into R dataframes.

I believe I need a for loop or maybe some solution with lapply or sapply. I have tried many options with loops or lapply, but the best I got was to create all the data.

The best I got so far was with the following code (adapted from a solution to open multiple CSV files):

library(foreign)

filenames <- list.files()

filelist <- lapply(filenames, read.spss, to.data.frame = TRUE)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col", 
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x)  
assign(x,filelist[[x]],envir=.GlobalEnv)))

With this code, I got all the files read, but as lists, not as data.frames. I don't know where I could put a "as.data.frame" or something like this to get what I want.

Maybe a solution would be to loop for all the files in the folder, so that the first element in the list (the first file), would be read as df.1, then df.2, etc. It doesn't matter what the names of the dataframes will be, I just need a simple code to read all of them into dataframes.

2 Answers2

0

At present, your object file_list is probably a character vector, not a list. If you prefer the resulting object to be a list, try:

library(foreign)

file_list <- as.list(list.files())
res <- lapply(file_list, read.spss, to.data.frame = TRUE)

This generates a vector of file names and coerces that vector to a list class object. Then, we apply read.spss to the list of file names using lapply, and assign the results to the object res.

Alternatively, you can apply read.spss straight to the character vector object (without coercing the vector to a list) using sapply:

file_vector <- list.files()
res <- sapply(file_vector, read.spss, to.data.frame = TRUE)

See also: Read multiple CSV files into separate data frames

George Wood
  • 1,914
  • 17
  • 18
0

It finally worked. The same code as I've put in the update of the question, but with the slight difference of using haven instead of foreign :

library(haven) 

filenames <- list.files()

filelist <- lapply(filenames, read_spss)

names(filelist) <- c("nic", "hon", "chi", "cr", "repdom", "ecu", "col", 
"sal", "par", "mex", "arg", "gua", "pan", "uru", "bra")

invisible(lapply(names(filelist), function(x) 
assign(x,filelist[[x]],envir=.GlobalEnv)))