Saving Stata file inside function in R

I am trying to move files from one folder to another. I have a data frame called "data", with "from" location, "to" and 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 copies only the first file. When I try to diagnose a problem by printing various terms inside the function (for example, adding print (copyto) as the last line of the function), it prints for each file specified in the data, which indicates that the function is executed for each line in the data, but it does not actually copy files beyond the first. How can i fix this?

+4
source share
3 answers

If you really do not need to read files in memory like data.frame using read.dta , I would suggest using file.copy , which will copy files using the computer's 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) 
+8
source

The problem is that write.dta not vectorized, and therefore none of them is your function. You can use mapply , as mapply noted, to vectorize your call to movefile or to vectorize movefile . One function you need to know is Vectorize , which is an easy way to vectorize any function.

 movefile <- Vectorize(movefile) 

This works in the general case, but may not be the most efficient or transparent method. You can also rewrite movefile for internal vectorization:

 movefile <- function(from, to, myfile) { readfile <- file.path(from, myfile) copyto <- file.path(to, myfile) mapply(function(f1, f2) write.dta(read.dta(f1), f2), readfile, copyto) } 
+4
source

You can use mapply , for example:

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

For example, check this out in the simplified version of movefile :

 data <- data.frame(from=1:2,to=2:3,myfile=c('a','b')) movefile <- function(from, to, myfile){ readfile <- paste(from, myfile,to, sep = "/") } mapply(movefile,data$from, data$to, data$myfile) [1] "1/a/2" "2/b/3" 
+3
source

Source: https://habr.com/ru/post/1491752/


All Articles