[R] function

Douglas Bates bates at stat.wisc.edu
Thu Nov 9 19:09:16 CET 2006

On 11/9/06, Bill Hunsicker <BHunsicker at rfmd.com> wrote:

> I am trying to create a function that i pass a data set to and have the
> function return some calculations based on data.
> Allow me to illustrate:
> myfunc <- function(lst,mn,sd){
>    lst <- sort(lst)
>    mn <- mean(lst)
>    sd <- sqrt(var(lst))
>    return(lst,mn,sd)
> }
> data1 <-c (1,2,3,4,5)
> data2 <- c(6,7,8,9,10)
> myfunc(data1,data1mn,data1sd)
> myfunc(data2,data2mn,data2sd)
> This snippet errors that data1mn not find and warns that return is
> deprecating!!!!!!!!!!!
> Can you help me?

It is the returning a vector of arguments without wrapping them as a
list that is deprecated.

You do not need to pass values to be returned as arguments to the function.

The simplest way of modifying your function is

myfunc <- function(dat)
   mn <- mean(dat)
   stddev <- sd(dat)
   list(data = dat, mean = mn, sd = stddev)

You could even make it into a one-liner as

myfunc <- function(dat) list(data = dat, mean = mean(dat), sd = sd(dat))

but it would be better R programming style to do some checking on the
argument 'dat' before trying to apply the mean and sd functions to it.

More information about the R-help mailing list