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

后端 未结 5 1749
梦如初夏
梦如初夏 2021-02-15 23:39

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

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-16 00:01

    I think this code I wrote converts to polar coordinates:

    # example data
    x<-runif(30)
    y<-runif(30)
    # center example around 0
    x<-x-mean(x)
    y<-y-mean(y)
    
    # function to convert to polar coordinates
    topolar<-function(x,y){
    
        # calculate angles 
        alphas<-atan(y/x)
    
        # correct angles per quadrant
        quad2<-which(x<0&y>0)
        quad3<-which(x<0&y<0)
        quad4<-which(x>0&y<0)
        alphas[quad2]<-alphas[quad2]+pi
        alphas[quad3]<-alphas[quad3]+pi
        alphas[quad4]<-alphas[quad4]+2*pi
    
        # calculate distances to 0,0
        r<-sqrt(x^2+y^2)
    
        # create output
        polar<-data.frame(alphas=alphas,r=r)
    
    }
    
    # call function
    polar_out<-topolar(x,y)
    # get out angles
    the_angles<-polar_out$alphas
    

提交回复
热议问题