Re: [R] how to use apply with two variables

2007-02-23 Thread Liaw, Andy
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@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}}

__
R-help@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.


[R] how to use apply with two variables

2007-02-23 Thread 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@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.