[R] function

Erik Iverson iverson at biostat.wisc.edu
Thu Nov 9 19:23:05 CET 2006


Bill -

The error is because data1mn is not defined as anything in your 
environment, nor are data1sd, data2mn, data2sd.  It appears as though 
you don't want to define these variables to pass into the function as 
arguments, but rather you want to compute them in your function.  In 
other words, your function does not depend on the values of these are 
before calling the function, you'd like to computer their values in your 
function.  Your function at this point only depends on the data set, 
called lst in your case, so you only need to pass that in.

The return() call is a different issue.  See ?return for an explanation 
of why you are receiving the warning message. You would like to return 
the result of more than one computation from your function.  You can use 
a list instead.  The version below does not return the sorted dataset as 
your function does, but only the mean and sd of the data set passed in. 
  You can modify the list() call to return sorted lst if you'd like. 
I've given the list components names.

myfunc <- function(lst) {
     lst <- sort(lst) #not needed to compute mean or sd, use if you want
     mn <- mean(lst)
     sd <- sqrt(var(lst)) #or use sd() in stats package, see ?sd
     list(mn=mn,sd=sd) #R returns the last expression w/out return()
}

 > myfunc(c(1,2,3,4))
$mn
[1] 2.5

$sd
[1] 1.290994

 > a <- myfunc(c(1,2,3,4))
 > a$mn
[1] 2.5
 > a$sd
[1] 1.290994
 > a
$mn
[1] 2.5

$sd
[1] 1.290994

Bill Hunsicker wrote:
> R-help,
>  
> 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?
>  
> Regards,
> Bill
>  
> 
> 
> 
> Bill Hunsicker
> RF Micro Devices
> 7625 Thorndike Road
> Greensboro, NC 27409-9421
> bhunsicker at rfmd.com
> 336-678-5260(w)
> 610-597-9985(m)
> 336-678-5088(lab)
> 
> 
>  
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list