简体   繁体   中英

R: Problems with appending dataframes to a list in a loop

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM