2016-04-15 20 views
0

stu.csvには850,000行と3列が含まれています。 2列目はIDの経度、3列目はIDの緯度です。 stu.csvファイルのデータは次のようになります。Rコードの実行速度が遅く、このコードを高速化および書き直す方法

ID longitude latitude 
    156 41.88367183 12.48777756 
    187 41.92854333 12.46903667 
    297 41.89106861 12.49270456 
    89 41.79317669 12.43212196 
    79 41.90027472 12.46274618 
    ...  ...   ... 

擬似コードは次のとおりです。それは経度と緯度と地球の表面上に2つのIDの間の距離を計算することを目的とする、任意の2つのIDから累積和を出力:

dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2 
    c = 2 * atan2(sqrt(a), sqrt(1-a)) 
    distance = 6371000 * c (where 6371000 is the radius of the Earth) 

このコードは以下の通りであるが、それは遅すぎる実行されます。どのように高速化し、コードを書き換えますか?ありがとうございました。

stu<-read.table("stu.csv",header=T,sep=","); 

    ## stu has 850,000 rows and 3 columns. 

    m<-nrow(stu); 

    distance<-0; 

    for (i in 1:(m-1)) 
    { 
     for (j in (i+1)) 
     {  
     dlon = stu[j,2] - stu[i,2]; 
     dlat = stu[j,3] - stu[i,3]; 
     a = (sin(dlat/2))^2 + cos(stu[i,3]) * cos(stu[j,3]) * (sin(dlon/2))^2; 
     c = 2 * atan2(sqrt(a), sqrt(1-a)); 
     distance <-distance+6371000 * c; 
     } 
    } 

    distance 
+3

アンO(N^2)のアルゴリズムは常にN = 850000 .... chinsoon12 @ –

+0

をいただき、ありがとうございます長い時間がかかるとしていますあなたの返信。私は問題を説明します – user2405694

+0

@ chinsoon12はい – user2405694

答えて

1

あなたのケースでは、我々はベクトル化することができます:

x <- read.table(text = "ID longitude latitude 
156 41.88367183 12.48777756 
187 41.92854333 12.46903667 
297 41.89106861 12.49270456 
89 41.79317669 12.43212196 
79 41.90027472 12.46274618", header= TRUE) 


x$laglon <- dplyr::lead(x$longitude, 1) 
x$laglat <- dplyr::lead(x$latitude, 1) 


distfunc <- function(long, lat, newlong, newlat){ 
    dlon = newlong - long 
    dlat = newlat - lat 
    a = (sin(dlat/2))^2 + cos(lat) * cos(newlat) * (sin(dlon/2))^2 
    c = 2 * atan2(sqrt(a), sqrt(1-a)) 
    6371000 * c 
} 

distfunc(x$longitude, x$latitude, x$laglon, x$laglat) 
308784.6 281639.6 730496.0 705004.2  NA 

は、取得するために、出力のCUMSUMを取ります総距離。万行で

、それは私のシステム上の周りに0.4秒かかります

+0

このエラーを解決するにはどうすればよいですか? http://stackoverflow.com/questions/36744127/an-error-about-vectorization-in-r – user2405694

-1

あなたが探しているものは、「ループをベクトル化する」と呼ばれています。 this related questionを参照してください。

基本的な考え方は、最初のセルがどのように処理されるかという保証がない限り、CPUは最初のセルの処理を終了してから2番目のセルに移動する必要があります。 2番目のセル。しかし、ベクトル計算の場合、その保証が存在し、可能な限り多くの要素を同時に処理することができ、高速化につながります。 (これがうまくいく理由は他にもありますが、それが基本的な動機です)。

ループ内でコードを書き直す方法については、Rのthis introduction〜を参照してください。それが累積距離である場合(。あなたがあるとして維持することができるはず計算の多く)

関連する問題