2013-12-19 3 views
0

적용 기능 사용과 같이 다음 알고리즘을 더 빨리 수행 할 수있는 방법이 있습니까?선형 모델 for for 루프; 적용 함수 사용?

set.seed(1) 
    n=1000 

    y=rnorm(n) 
    x1=rnorm(n) 
    x2=rnorm(n) 

    lm.ft=function(y,x1,x2) 
     return(lm(y~x1+x2)$coef) 

    res=list(); 
    for(i in 1:n){ 
     x1.bar=x1-x1[i] 
     x2.bar=x2-x2[i] 
     res[[i]]=lm.ft(y,x1.bar,x2.bar) 
    } 

답변

4

사용 lm.fit 대신 lm는 :

fun1 <- function() { 
    res=list(); 
    for(i in 1:n){ 
    x1.bar=x1-x1[i] 
    x2.bar=x2-x2[i] 
    res[[i]]=lm.ft(y,x1.bar,x2.bar) 
    } 
    res 
} 

lm.ft2 <- function(y,x1,x2) lm.fit(cbind(1,x1,x2), y)$coef 

fun2 <- function() { 
    res2 <- sapply(seq_along(y), function(i, x1, x2, y) { 
    x1.bar=x1-x1[i] 
    x2.bar=x2-x2[i] 
    lm.ft2(y,x1.bar,x2.bar) 
    }, x1=x1, x2=x2, y=y) 
    res2 
} 

library(microbenchmark) 
microbenchmark(res <- fun1(), res2 <- fun2(), times=10) 

#Unit: milliseconds 
#   expr  min   lq median  uq  max neval 
#res <- fun1() 147.776069 149.580443 152.64378 159.53053 166.06834 10 
#res <- fun2() 8.760102 9.004934 10.34582 10.58757 13.86649 10 


all.equal(
    unname(t(res2)), 
    unname(do.call(rbind,res)) 
) 
#[1] TRUE 
+0

속도 향상의 대부분은 lm.fit을 사용하는 것 같다. FOR 루프에서 속도를 줄이는 다른 방법이 있습니까? 사실, 이중 루프를 사용해야합니다. – user1690124

+0

이중 'for' 루프가 필요하다고 생각하지 않습니다. 그러나'for '루프는 실제로 R에서 꽤 빠릅니다 (그리고'lapply'와 친구들은 더 빠르지 않습니다). 루프 내부에서 일반적으로하는 일은 시간 소모적 인 부분입니다. 벡터화 된 기능을 사용하면 최고의 속도 향상을 얻을 수 있습니다. – Roland

+0

http://stackoverflow.com/questions/2908822/speed-up-the-loop-operation-in-r/8474941#8474941 –