how to return number of decimal places in R

前端 未结 12 1177
走了就别回头了
走了就别回头了 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:36

    Not sure why this simple approach was not used above (load the pipe from tidyverse/magrittr).

    count_decimals = function(x) {
      #length zero input
      if (length(x) == 0) return(numeric())
    
      #count decimals
      x_nchr = x %>% abs() %>% as.character() %>% nchar() %>% as.numeric()
      x_int = floor(x) %>% abs() %>% nchar()
      x_nchr = x_nchr - 1 - x_int
      x_nchr[x_nchr < 0] = 0
    
      x_nchr
    }
    
    > #tests
    > c(1, 1.1, 1.12, 1.123, 1.1234, 1.1, 1.10, 1.100, 1.1000) %>% count_decimals()
    [1] 0 1 2 3 4 1 1 1 1
    > c(1.1, 12.1, 123.1, 1234.1, 1234.12, 1234.123, 1234.1234) %>% count_decimals()
    [1] 1 1 1 1 2 3 4
    > seq(0, 1000, by = 100) %>% count_decimals()
     [1] 0 0 0 0 0 0 0 0 0 0 0
    > c(100.1234, -100.1234) %>% count_decimals()
    [1] 4 4
    > c() %>% count_decimals()
    numeric(0)
    

    So R does not seem internally to distinguish between getting 1.000 and 1 initially. So if one has a vector input of various decimal numbers, one can see how many digits it initially had (at least) by taking the max value of the number of decimals.

    Edited: fixed bugs

提交回复
热议问题