[R] how to use apply with two variables

Liaw, Andy andy_liaw at merck.com
Fri Feb 23 20:38:59 CET 2007


Yes.  Just try it and see.

BTW, your usage of return() is not recommended anymore.  This is
probably easier:

myfun<-function(x) c(mean=mean(x), sd=sd(x))
out <- apply(mat, 1, myfun)
## or...
out2 <- cbind(mean=rowMeans(mat), sd=sd(t(mat))) 

Andy


From: Serguei Kaniovski
> 
> Hi,
> 
> this is a made-up example. Function "myfun" returns two 
> arguments. Can "apply" be used so that "myfun" is called only once?
> 
> Thanks
> Serguei
> 
> mat<-matrix(runif(50),nrow=10,ncol=5)
> 
> myfun<-function(x) {
>  mymean<-mean(x)
>  mysd<-sd(x)
>  return(mymean,mysd)
> }
> 
> out1<-t(apply(mat,1,function(x) myfun(x)$mymean))
> out2<-t(apply(mat,1,function(x) myfun(x)$mysd))
> 	[[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.
> 
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}



More information about the R-help mailing list