【问题标题】:Speed up looping code for coordinate conversion加速循环代码进行坐标转换
【发布时间】:2015-07-03 06:36:40
【问题描述】:

我有一个树干及其位置的数据集,最初是在绘图坐标中。我需要将这些坐标转换为 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 

非常感谢!

【问题讨论】:

    标签: r loops coordinates


    【解决方案1】:

    最好的办法是向量化操作而不是使用循环。你可以这样做:

    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
    

    【讨论】:

    • 完美运行!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多