加快循环代码以进行坐标转换

时间:2015-04-24 15:12:41

标签: r loops coordinates

我有一个树干数据集及其位置,最初是绘图坐标。我需要将这些坐标转换为utm坐标。我编写了以下函数来将我们的绘图坐标转换为utm坐标,并使用以下脚本在整个数据集上运行它。我遇到的问题是我总共有261403个词干,并且脚本运行时间非常长。我知道循环通常很慢,应该避免。关于如何不使用循环执行此操作的任何建议?

定义功能:

    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)
    }

循环:

    for (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])
    }

以下是一些示例数据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 

非常感谢!

1 个答案:

答案 0 :(得分:2)

最好的事情是矢量化操作而不是使用循环。你可以这样做:

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