0

I want to iterate along a character vector, read from a SAS file containing a string in the character vector as part of the path, then write this data frame into my database. Below is an example of my code that isn't working.

  for (j in c("table1", "table2")) {
    SAS_File_Path <- paste("C:/SAS_files/", j, ".sas7bdat", sep = "")
    if (file.exists(SAS_File_Path)){
        j <- read.sas7bdat(SAS_File_Path)
        sqlSave(ch, j, rownames = FALSE, append = TRUE)
    }
}

The for loop above seems to paste the the path together correctly making something like C:/SAS_files/table1.sas7bdat but then it gets assigned to a data frame named j rather than table1. I need the data frame to be named table1 so I can append it to a pre-existing table in my data frame. Ultimately I want to iterate along a character vector and read a file into into a data frame assigned to the string in that element of the vector.

Any guidance would be greatly appreciated

JanLauGe
  • 2,297
  • 2
  • 16
  • 40
Pat_W
  • 1
  • 1
    Doesn't `sqlSave` have a `tablename` argument? If so, problem solved. – joran Apr 04 '16 at 21:11
  • 1
    It seems very strange that you are using `j` both as your loop index as well as a variable name for the data frame. Why not `dat <- read.sas7bdat(SAS_File_Path)`? Then using joran's suggestion, `sqlSave(ch, dat = dat, tablename = j, rownames = FALSE, append = TRUE)` – Gregor Thomas Apr 04 '16 at 21:11
  • 2
    (...and the usual idiom for this general task in R is to create a named list up front and assign each data frame to the list in turn) – joran Apr 04 '16 at 21:16
  • 1
    See [How to make a list of data frames](http://stackoverflow.com/a/24376207/903061) for examples and reasons why. – Gregor Thomas Apr 04 '16 at 21:19
  • Thanks @joran and @Gregor! – Pat_W Apr 05 '16 at 13:37

0 Answers0