Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Stata File Within a Function in R

I am trying to move files from one folder to another. I have a data frame called "data" with the "from" location, "to" location, and the file name "myfile."

library(foreign)


movefile <- function(from, to, myfile){
  readfile <- paste(from, myfile, sep = "/")
  temp <- read.dta(readfile)
  copyto <- paste(to, myfile, sep = "/")
  write.dta(temp, copyto)
}

When I call the function with the following line of code:

movefile(data$from, data$to, data$myfile)

It only copies over the first file. When I try and diagnose the problem by printing various terms within the function (e.g. adding print(copyto) as the final line of the function), it prints for every file listed in data, indicating that the function is being run for every row in data, but it does not actually copy the files beyond the first one. How can I correct this?

like image 476
Michael Avatar asked Dec 06 '22 06:12

Michael


1 Answers

Unless you really need to read the files into memory as a data.frame using read.dta, I would suggest using file.copy, which will copy files using the computer file system.

 original.files <- do.call('file.path', data[c('from','myfile')])
 new.files <- do.call('file.path', data[c('to','myfile')])

 # overwrite will overwrite, so make sure you mean to do this 
 file.copy(from = original.files, to = new.files, overwrite = TRUE)
like image 190
mnel Avatar answered Dec 11 '22 11:12

mnel