0

I am wondering if there is a way to iterate converting multiple .rds files (all in the same directory "c:/Qualtrics) to .csv. I have used convert to convert a single .rds but I haven't been able to figure out how to iterate the process (I have over 500 of the files to convert).

I am also a beginner R user.

Mannladar
  • 3
  • 1
  • 3
  • In order to convert .rds to .csv, the object stored should be a data frame. You can use `list.files` to get file names for all .rds files and use for loop to convert them to csv files. – yusuzech Nov 21 '19 at 23:23
  • Have a look at the lapply function. – Daniel V Nov 21 '19 at 23:29
  • yifyan, I have used list.files to get all of the files names but I haven't been able to fashion a for loop that will work. – Mannladar Nov 21 '19 at 23:33
  • Can you provide us the codes you use or error messages you encountered? – yusuzech Nov 21 '19 at 23:53
  • I use this for a single conversion 'convert("SV_00SgIJPVvm8Qtsp.rds","SV_00SgIJPVvm8Qtsp.csv")', however I don't know how to iterate it because 'convert' needs the original extention and the new extention. I used Qualtrics <- list.files(directory) to get a file name list. – Mannladar Nov 21 '19 at 23:56
  • `convert` is not a function in baseR, what package is that function from? If you can convert one file, then you can convert multiple. But without reproducible example, we can't help you much. I suggest that you go over R fundamentals such as loop, function, etc. – yusuzech Nov 22 '19 at 00:32

1 Answers1

0

I am assuming you are using package rio which includes a convert function. Without reproducible data I can't test it, but it should be enough to get you started. The line stripping the extension and adding ".csv" assumes that there is only one "." in the filename. If that is not the case, it will be a bit more complicated.

library(rio)
Qualtrics <- list.files(directory)   # This gives you your input files
# Split off the extension and add .csv extension
QualtricsCSV <- paste0(sapply(strsplit(Qualtrics, "\\."), "[", 1), ".csv")
setwd(directory)
for (i in seq(length(x)) {
     convert(Qualtrics[i], QualtricsCSV[i])
}
dcarlson
  • 10,936
  • 2
  • 15
  • 18
  • 1
    Thanks dcarlson. So that converts the list of files to .csv but how do I use that to convert the actual .rds files to .csv? – Mannladar Nov 27 '19 at 22:46
  • I figured it out from this question: https://stackoverflow.com/questions/15707039/proper-phrasing-for-a-loop-to-convert-all-dta-files-to-csv-in-a-directory?rq=1 I ended up using for (Qualtrics in Sys.glob('*.rds')) write.csv(readRDS(Qualtrics), file = gsub('rds$','csv', Qualtrics)) which converted all of the files in the directory to .csv. – Mannladar Nov 27 '19 at 23:53