1

I have code in which I am sourcing multiple codes one after the other. Something like below

source("t1.r")
source("t2.r")
source("t3.r")
source("t4.r")

While running this main script if any source statement gives an error, I don't want to source any remaining scripts (i.e. don't want to run any subsequent statements).

I don't want to write if error condition after every source statement. I want to do something universal and at the beginning only.

What change should I do in the main script to do this?

8
  • Are these files multiple lines of codes? Or are there functions within these files. You can look at stop function Commented Feb 21, 2016 at 7:17
  • Yes they are multiple lines of codes, but there are no functions inside those. Commented Feb 21, 2016 at 7:18
  • stop function, i will have to write after every statement, won't I? That will too inefficient, since there are a lot of source statements in the main script. Commented Feb 21, 2016 at 7:19
  • 1
    Why would you write the source call 20 times for 20 scripts? Iterate on the scripts names/paths and handle exception within the loop, don't copy/paste as per DRY principles. Commented Feb 21, 2016 at 7:54
  • 1
    If you put those source statements in a file (say named all.R), then you run source("all.R") and it will stop as soon as there is an error. Do you also want to know which script produced the error? Commented Feb 21, 2016 at 7:55

1 Answer 1

1

Edited as per suggested by Nicola and RHertel

setwd("/Users/xxxx/Desktop/Sub")
scripts<-list.files(pattern="*.R")         

for (f in scripts)
{
  c<-try(source(f))                        
  ifelse (class(c)!="try-error", print(paste("Script Sourced:", f,sep=" ")), setwd("/Users/xxxx/Desktop")             
}

This script prints the scripts sourced. That way you can recognise which didnt get sourced.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Nicola and RHertel. New code is much improved. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.