How to change a value in a list of R files?

Asked

Viewed 77 times

3

I have a list of files, example 001.R and 002.R. Usually I do:

for (i in c('001.R' e '002.R')){source(i)}

However, there is now a parameter within each file that I need to change. No 001.R and 002.R is written:

x<-1:10
if(M==TRUE){write.csv(x, file = "foo.csv")}

Then how to set the value of M (TRUE or FALSE) before entering the for?

  • 1

    Although it is possible to do this, I believe that the most recommended is to turn these scripts into functions and add an argument to the function. Case

1 answer

4


I have written two files with the filenames of the question. The first one has

# '001.R'
if(M){
  print("Script 1")
}

and similar in the file '002.R'. Note that is not necessary the test M == TRUE because M is already or TRUE or FALSE. (And it would be better, safer, to use isTRUE(M).)

Then the cycle for gets like this:

valor <- c(TRUE, FALSE)
fich <- c('001.R', '002.R')
for (i in seq_along(fich)){
  M <- valor[i]
  source(fich[i])
}
#[1] "Script 1"

I mean, I attribute it to M a value before the source and this value is used by the script code because it is in the .GlobalEnv.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.