Reputation: 1295
I'm new to writing functions in R and want to write a function that creates multiple outputs, yet I'd like to mask the output of certain objects such that they are calculated and can be called, but aren't directly output when the function is fun. For example:
fun <- function(x){
mean <- mean(x)
sd <- sd(x)
return(list(sd = sd, mean = mean))
}
x <- rnorm(100)
fun(x)
Here, I would like the mean to be reported when fun(x) is run and the sd to be calculated but not reported (when I take sd out of the list, I can no longer call it later). Thanks for any help!
Upvotes: 1
Views: 455
Reputation: 15163
There are two ways to do this. The first is to use invisible
as shown by @SenorO. The more complicated way is to create a new class and override the print method. If you create a new class, then every time the object gets printed, only the mean will show up:
print.myclass<-function(x){
cat("Mean is:",x$mean ,"\n")
}
fun <- function(x){
mean <- mean(x)
sd <- sd(x)
ret<-list(sd = sd, mean = mean)
class(ret)<-"myclass"
ret
}
You can still access the values in the class as if it were a list, and if you want the actual underlying list, call unclass:
> x<-fun(rnorm(100))
> x
Mean is: -0.03470428
> x$mean
[1] -0.03470428
> x$sd
[1] 0.9950132
> unclass(x)
$sd
[1] 0.9950132
$mean
[1] -0.03470428
Upvotes: 6
Reputation: 17432
Using print
and invisible
fun <- function(x){
print(mean <- mean(x))
sd <- sd(x)
return(invisible(list(sd = sd, mean = mean)))
}
Resulting in:
> y = fun(x)
[1] -0.01194926
> y$sd
[1] 0.9474502
Upvotes: 3