How to batch process converting all .sav to flat file that are in a folder in R ?

你。 提交于 2019-12-24 19:43:23

问题


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")

回答1:


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
}


来源:https://stackoverflow.com/questions/48693759/how-to-batch-process-converting-all-sav-to-flat-file-that-are-in-a-folder-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!