[R] How can we make a vector call a function element-wise efficiently?

zhaoxing731 zhaoxing731 at yahoo.com.cn
Fri Feb 11 06:12:40 CET 2011


Hello
	I have a time-comsuming program which need to simplify, I have tested the annotated program as follow:

> #define function which will be call

> calsta <- function(c, n=100000) 
+ { 
+   i <- seq(from=0, length=c) 
+   logx <- lchoose(NT-n, CT-i) + lchoose(n, i) 
+   logmax <- max(logx) 
+   logmax + log(sum(exp(logx - logmax))) 
+ } 
> CT=6000	#assignment to CT
> NT=29535210	#assignment to NT
> 
> vec<-c(2331,524,918,218,1100,547,289,1167,450,1723)
> vec
 [1] 2331  524  918  218 1100  547  289 1167  450 1723
> vec<-rep(vec,1000)#replicate the vec 1000 times
> length(vec)
[1] 10000 

> #then I'd like to make vector "vec" call function calsta element-wise
> #and save the output to vector "result"

> system.time(result<-sapply(vec,calsta))
   user  system elapsed 
  26.45    0.03   26.70 
> 
> system.time(for (i in 1:10000) result[i]=calsta(vec[i]))
   user  system elapsed 
  27.74    0.14   28.94 

I have about  300,000 such 26.70/ 28.94 seconds, so the approximate computation time is 100 days
What a terrible thing to do!!!
Any modification, nomatter how subtle, will be a big help for me

Thank you in advance

Yours sincerely
 



ZhaoXing
Department of Health Statistics
West China School of Public Health
Sichuan University
No.17 Section 3, South Renmin Road
Chengdu, Sichuan 610041
P.R.China

__________________________________________________
¸Ï¿ì×¢²áÑÅ»¢³¬´óÈÝÁ¿Ãâ·ÑÓÊÏä?



More information about the R-help mailing list