Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to automatically change a line in several R scripts?

Tags:

replace

r

edit

I have 50 R scripts that I need to change the same line for all of them. Is there a way to do it all of them at the same time instead of one by one using "find" and "replace"?

like image 208
MSS Avatar asked Mar 08 '23 04:03

MSS


1 Answers

Loop through the files, read line by line (readLines gives a character vector), then update the Nth row, and output to new file:

lapply(list.files(path = ".", pattern = "*.R", full.names = TRUE),
       function(i){
         x <- readLines(i)
         # if we want for example change the 6th row:
         x[ 6 ] <- "# MY NEW LINES"
         # then write output
         write(x, file = paste0("myCleanOutput/folder/path/", basename(i)))
       })

But, if all R scripts are the same, maybe use Passing command line arguments to R CMD BATCH and have only 1 Rscript file which takes arguments.

like image 133
zx8754 Avatar answered Apr 06 '23 22:04

zx8754