R: Converting cartesian coordinates to polar coordinates, and then calculating distance from origin

后端 未结 2 784
轻奢々
轻奢々 2021-02-15 23:45

I\'ve been looking for a solution to convert cartesian coordinates (lat, long) that I have to polar coordinates in order to facilitate a simulation that I want to run, but I hav

相关标签:
2条回答
  • 2021-02-16 00:00

    For x-y coordinates that are in the same units (e.g. meters rather than degrees of latitude and degrees of longitude), you can use this function to get a data.frame of jump sizes and turning angles (in degrees).

    getSteps <- function(x,y) {
        d <- diff(complex(real = x, imaginary = y))
        data.frame(size = Mod(d), 
                   angle = c(NA, diff(Arg(d)) %% (2*pi)) * 360/(2*pi))
    }
    
    ## Try it out   
    set.seed(1)
    x <- rnorm(10)
    y <- rnorm(10)
    getSteps(x, y)
    #        size     angle
    # 1 1.3838360        NA
    # 2 1.4356900 278.93771
    # 3 2.9066189 101.98625
    # 4 3.5714584 144.00231
    # 5 1.6404354 114.73369
    # 6 1.3082132 135.76778
    # 7 0.9922699  74.09479
    # 8 0.2036045 141.67541
    # 9 0.9100189 337.43632
    
    ## A plot helps check that this works
    plot(x, y, type = "n", asp = 1)
    text(x, y, labels = 1:10)
    

    enter image description here

    0 讨论(0)
  • 2021-02-16 00:05

    Since it is fairly straight forward, you can write your own function. Matlab-like cart2pol function in R:

    cart2pol <- function(x, y)
    {
      r <- sqrt(x^2 + y^2)
      t <- atan(y/x)
    
      c(r,t)
    }
    
    0 讨论(0)
提交回复
热议问题