How to batch process converting all .sav to flat f

2019-08-23 11:59发布

Below is my code to convert .sav to a flat file format that works well, my issue raises when I have more than 50 files. Any suggestions on how I can process all the files available in a folder in a loop ?

  #load library foreign to read spss 
  library(foreign) 

  #set working directory first 
  setwd("M:\\Files\\Linear Reg") 

  #read .sav file 
  data <-read.spss('Computed_Copy.sav', to.data.frame=TRUE,use.value.labels=FALSE) 
  write.csv(data, "Computed_Copy.csv")

标签: r spss
1条回答
放我归山
2楼-- · 2019-08-23 12:18

First list all files in your folder with ending .sav

files <- list.files(path = 'your/path/tofolder', pattern = '.sav')
for(f in files){ # iterate over them 
  data <-read.spss(f, to.data.frame=TRUE,use.value.labels=FALSE) 
  write.csv(data, paste0(strsplit(f, split = '.', fixed =  T)[[1]][1], '.csv')) 
# the stringsplit removes the wrong ending and the paste adds .csv
}
查看更多
登录 后发表回答