how to return number of decimal places in R

前端 未结 12 1143
走了就别回头了
走了就别回头了 2020-12-01 08:25

I am working in R. I have a series of coordinates in decimal degrees, and I would like to sort these coordinates by how many decimal places these numbers have (i.e. I will w

12条回答
  •  -上瘾入骨i
    2020-12-01 08:37

    Vector solution based on daroczig's function (can also deal with dirty columns containing strings and numerics):

    decimalplaces_vec <- function(x) {
    
      vector <- c()
      for (i in 1:length(x)){
    
        if(!is.na(as.numeric(x[i]))){
    
          if ((as.numeric(x[i]) %% 1) != 0) {
            vector <- c(vector, nchar(strsplit(sub('0+$', '', as.character(x[i])), ".", fixed=TRUE)[[1]][[2]]))
    
    
          }else{
            vector <- c(vector, 0)
          }
        }else{
          vector <- c(vector, NA)
        }
      }
      return(max(vector))
    }
    

提交回复
热议问题