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