Question

I'm new to writing functions and would like to suppress the output if a given argument in a function is not reported without having to write multiple return() for each potential statement. For example:

fun <- function(x1,x2, y){
    if(missing(y)){result<- x1+x2}
    if(!missing(y)){ols<-lm(y ~ x1 + x2)}  
return(list(result = result, 
            ols = ols))

}   

x1 <- rnorm(100)
x2 <- rnorm(100)

fun(x1,x2)

When you run this, you get an error since the OLS isn't reported (if you include a y, you get the same problem for the object 'result'). Without including a specific return() function within each if statement, can you suppress one of the return elements? Thanks for any and all thoughts

Was it helpful?

Solution

You could use compact from plyr, in combination with initializing result and ols objects as NULL at the start.

library(plyr)

fun <- function(x1, x2, y){
  result = ols = NULL
  if(missing(y))
    result <- x1+x2
  if(!missing(y))
    ols <- lm(y ~ x1 + x2)
  return(compact(list(result = result, 
          ols = ols)))

}   

x1 <- rnorm(100)
x2 <- rnorm(100)

fun(x1,x2)

plyr::compact removes NULL elements from a list

OTHER TIPS

Use the try function for error handeling:

try(fun(x1,x2),silent=TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top