Home > front end >  SAS Import to R
SAS Import to R

Time:06-23

The following code works, but I want to retain the original dataset names for the data frames. How can this be done?

path <- 'C:/path2file/'
print(path)
files <- list.files(path = path, pattern="*.sas7bdat", full.names=FALSE)
print(files)

mydf <- list()
for (i in 1:length(files)){
  filename <- paste0(path, files[i])
  print(filename)
  mydf[[i]] <- haven::read_sas(data_file=filename)
  print(names(mydf[[i]]))
  eval(parse(text = paste0("mydf_", i, " <- haven::read_sas(data_file=filename)")))
}

CodePudding user response:

Do you mean like this:

library(haven)
df1 <- data.frame(x = rnorm(10))
df2 <- data.frame(y = rnorm(10))

haven::write_sas(df1,"./df1.sas7bdat")
haven::write_sas(df2,"./df2.sas7bdat")

path = "./"
files <- list.files(path, pattern = "*.sas7bdat", full.names = FALSE)

for(i in 1L:length(files)){
  filename <- paste0(path, files[i])
  assign(paste0("mydf_",files[i]),haven::read_sas(filename))
}
> mydf_df1.sas7bdat
# A tibble: 10 × 1
        x
    <dbl>
 1  0.307
 2 -0.173
 3 -0.581
 4 -0.300
 5  1.31 
 6  0.473
 7 -1.34 
 8  2.70 
 9  0.508
10  0.681
> mydf_df2.sas7bdat
# A tibble: 10 × 1
        y
    <dbl>
 1 -1.20 
 2  0.939
 3  0.918
 4 -1.48 
 5  0.240
 6 -0.697
 7  0.730
 8 -0.191
 9  1.26 
10  1.71
  •  Tags:  
  • r
  • Related