2021年3月11日星期四

Convert a Data Frame of Coordinates found in different units to one unit

I want to modify data frame columns to have coordinates in the same units. They are found in these units; dec_deg, deg_dec_min, or NA. Here is a reproducible example:

Long <- c("","E 9.64740","E 9°35.988'","","-16.5708666666667","109.395389",  "-16.6455666666667","W047 22.044", "-16.5437166666667")    Lat <- c("","S 2.40889","N 00°27.799","14.0011","","-0.632361",           "13.9622333333333","S00 37.952", "14.0532")    Date <- as.Date(c('2010-11-1','2008-3-25','2007-3-14', '2010-11-1','2008-3-25','2007-3-14','2010-11-1','2008-3-25','2007-3-14'))  Site.ID <- c("MWA-S", "MWA-S","MWA-S","BAM","BAM","BAM","BAM","BAM","BAO")  No.ID <- c(34, 5,16,46,2,85,60,1,30)    DF <- data.frame(No.ID, Site.ID, Date, Lat, Long)  

I referenced this question to clean up my columns by using the measurements library and removing unwanted characters. But that fails b/c the coordinates are not in the same units. I want to create a function like this one that conditionally does the conversion.

library(measurements)    coord2dec <- function(x) {    x <- as.character(x)    x <- do.call(rbind, strsplit(x, split='N'|'E'|'S'|'W'|'°'))#maybe where to #apply my conditions    x <- apply(x, col, function(y) {      y <- as.numeric(y)      measurements::conv_unit(y$col, from = 'deg_dec_min', to = 'dec_deg')    })    return(x)  }    new_df <- apply(DF2, coord2dec)  

The above fails b/c I may be missing other conditions & formatting. My goal is to create a function that identifies if a coordinate is deg_dec_min (dd mm.mmmm) or a dec_deg (dd.ddddd). Then it would convert W/S to -; Remove "NSEW" and whitespace and replaces degree with space. Desired output would convert the example data frame to the following.

  No.ID Site.ID       Date       Lat              Long  1    34   MWA-S 2010-11-01       NA               NA       2     5   MWA-S 2008-03-25   -2.408890         9.647400  3    16   MWA-S 2007-03-14    0.463317         9.599800  4    46     BAM 2010-11-01   14.0011         -16.5708667  5     2     BAM 2008-03-25       NA               NA          6    85     BAM 2007-03-14   -0.632361      109.395389  7    60     BAM 2010-11-01   13.96223333    -16.6455666666667  8     1     BAM 2008-03-25   -0.632533      -47.367400  9    30     BAO 2007-03-14   14.0532        -16.5437166666667  
https://stackoverflow.com/questions/66559740/convert-a-data-frame-of-coordinates-found-in-different-units-to-one-unit March 10, 2021 at 02:54PM

没有评论:

发表评论