1

I'm trying to import several SAS datafiles from a folder and then save them back into the folder as R dataframes with the same original SAS dataset name. Everything works except I can't figure out how to save the file with the original file name (i.e., I can't figure out the x in > save(xxx, file = ...).

The code I've tried is as follows:

path <- "path to folder with sas files"

list.files(pattern=".sas7bdat$")
list.filenames<-list.files(pattern=".sas7bdat$")

for (i in 1:length(list.filenames)){
  assign(list.filenames[i], read_sas(list.filenames[i]))
  filename <- paste(list.filenames[i]) 
  save(list.filenames[i],file = paste0(path, paste(list.filenames[i], "Rdat", sep = ".")))
  }

doesn't work...

for (i in 1:length(list.filenames)){
  assign(list.filenames[i], read_sas(list.filenames[i]))
  filename <- paste(list.filenames[i]) 
  save(list.filenames[[i]],file = paste0(path, paste(list.filenames[i], "Rdat", sep = ".")))
  }

doesn't work

for (i in 1:length(list.filenames)){
  assign(list.filenames[i], read_sas(list.filenames[i]))
  filename <- paste(list.filenames[i]) 
  save(filename,file = paste0(path, paste(list.filenames[i], "Rdat", sep = ".")))
  }

Any help on figuring out how to save the files with the original names from list.filenames[i]?

Ryan
  • 59
  • 9
  • You can grab individual elements of a list by index with list[[i]]. Try putting all of your calls to the list in double, rather than single brackets. – colin May 25 '18 at 15:42

1 Answers1

0

Use the "list" argument of save. Something like

path <- "path to folder with sas files"

list.filenames <- list.files(path, pattern="\\.sas7bdat$")

for (i in list.filenames) {
    datName <- tools::file_path_sans_ext(i)
    assign(datName, read_sas(i))
    save(list=datName, file = paste0(path, paste(datName, "Rdat", sep = ".")))
}

would work. Also, I imagine you want pattern=".sas7bdat$" as pattern="\\.sas7bdat$, since "." is a wildcard in regex.

user387832
  • 503
  • 3
  • 8
  • Thanks. This still runs into the problem I was trying to solve. It saves the tibble in a folder with the appropriate name but when I load it back into R all the dataframes are called "tb". I'm trying to take a sas datafile named, for example, "stock", save to a folder as a tibble or dataframe as "stock" then when I independently load it back into R it will be named "stock", not "tb". If you have any other ideas for this I'd appreciate it as I'm pretty stuck. Thanks. – Ryan May 25 '18 at 16:54
  • I see. I've amended my answer. – user387832 May 25 '18 at 17:30
  • That works perfect. Thank you so much for helping me out, this would have taken me forever. I've never see the tools::file_path_sans_ext(). Thanks again, I really appreciate your assistance. – Ryan May 25 '18 at 19:16