r - Speed up looping code for coordinate conversion -


i have data set of tree stems , position, in plot-coordinates. need convert these coordinates utm coordinates. have written following functions convert our plot coordinates utm coordinates , following script run on entire dataset. problem i've encountered have 261403 stems total, , script has been taking incredibly long time run. know loops in general slow , should avoided. advice on how perform without using loop?

defining functions:

    newcoords_x=function(gx,gy)     {         rot_x <- gx*cos(-0.031989084) - gy*sin(-0.031989084)       rot_y<- gx*sin(-0.031989084) + gy*cos(-0.031989084)        utm_x<-rot_x+625774       utm_y<-rot_y+1011776         return(utm_x)     }      newcoords_y=function(gx,gy)     {        rot_x <- gx*cos(-0.031989084) - gy*sin(-0.031989084)       rot_y<- gx*sin(-0.031989084) + gy*cos(-0.031989084)         utm_x<-rot_x+625774       utm_y<-rot_y+1011776       return(utm_y)     } 

the loop:

    (i in 1:length(x$tag))     {       x$utm_x[i]=newcoords_x(x$gx[i], x$gy[i])       x$utm_y[i]<-newcoords_y(x$gx[i], x$gy[i])     } 

here sample data, x,

    tag    gx    gy      2  994.1 488.3      4  990.5 488.9        6  993.5 498.3       7  992.7 469.3      8  981.9 473.5      13 983.0 452.6  

thanks much!

best thing vectorize operations instead of using loop. can do:

transform(x, utm_x=gx*cos(-0.031989084) - gy*sin(-0.031989084) + 625774            , utm_y=gx*sin(-0.031989084) + gy*cos(-0.031989084) + 1011776)  #  tag    gx    gy    utm_x   utm_y #1   2 994.1 488.3 626783.2 1012232 #2   4 990.5 488.9 626779.6 1012233 #3   6 993.5 498.3 626782.9 1012242 #4   7 992.7 469.3 626781.2 1012213 #5   8 981.9 473.5 626770.5 1012218 #6  13 983.0 452.6 626771.0 1012197 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -