1

I am running a data set (in the example, "data object ") through several different functions in R and concatenating the numeric results at the end. See:

a<-median((function1(x=1,dataobject,reps=500)),na.rm=TRUE)
b<-median((function2(x=1,dataobject,reps=500)),na.rm=TRUE)
c<-median((function3(x=1,dataobject,reps=500)),na.rm=TRUE)

d<-median((function4(x=1,dataobject,reps=500)),na.rm=TRUE)
e<-median((function5(x=1,dataobject,reps=500)),na.rm=TRUE)
f<-median((function6(x=1,dataobject,reps=500)),na.rm=TRUE)

c(a,b,c,d,e,f)

However, some of the functions cannot be run with the data set I am using, and so they return an error; e.g. "function3" can't be run so when it gets to the concatenation step it gives "Error: object 'e' not found" and does not return anything. Is there any way to tell R at the concatenation step to assign a value of "NA" to an object that is not found and continue to run the rest of the code instead of stopping? So that the return would be

[1] 99.233 75.435 77.782 92.013 NA 97.558 

A simple question, but I could not find any other instances of it being asked. I originally tried to set up a function to run everything and output the concatenated results, but ran into the same problem (when a function can't be run, the entire wrapper function stops as well and I don't know how to tell R to skip something it can't compute).

Any thoughts are greatly appreciated! Thanks!

Fishy
  • 11
  • 2

1 Answers1

0

A couple of solutions I can think of,

  1. Initialize all the variables you plan to use, so they have a default value that you want.

    a = b = c = d = e = NA

then run your code. If an error pops up, you will have NA in the variable.

  1. Use "tryCatch". If you are unaware what this is, I recommend reading on it. It lets you handle errors.

Here is an example from your code,

tryCatch({
  a<-median((function1(x=1,dataobject,reps=500)),na.rm=TRUE)
},
error = function(err){
  print("Error in evaluating a. Initializing it to NA")
  a <<- NA
})
Community
  • 1
  • 1
Avinash
  • 2,521
  • 4
  • 21
  • 35
  • This is excellent! Great simple fix with initializing the variables, and using tryCatch allowed me to put everything in a function and run it. Thank you for introducing me to tryCatch and thank you so much for the help! I want to up vote but I don't have enough reputation. When I do I will come back and pay my debts! – Fishy Apr 25 '15 at 14:42
  • @Fishy Accept the answer if it was useful for you. (The tick mark beside the answer) – Avinash Apr 25 '15 at 15:45