Test for numeric elements in a character string

前端 未结 6 2073
我在风中等你
我在风中等你 2020-12-05 01:38

I want to test a character string and see which elements could actually be numeric. I can use regex to test for integer successful but am looking to see which elements have

6条回答
  •  余生分开走
    2020-12-05 02:23

    Inspired by the answers here, my function trims leading and trailing white spaces, can handel na.strings, and optionally treats NA as numeric like. Regular expression was enhanced as well. See the help info for details. All you want!

    check if a str obj is actually numeric
    @description check if a str obj is actually numeric
    #' @param x a str vector, or a factor of str vector, or numeric vector. x will be coerced and trimws.
    #' @param na.strings case sensitive strings that will be treated to NA.
    #' @param naAsTrue whether NA (including actual NA and na.strings) will be treated as numeric like
    #' @return a logical vector (vectorized).
    #' @export
    #' @note Using regular expression
    #' \cr TRUE for any actual numeric c(3,4,5,9.9) or c("-3","+4.4",   "-42","4L","9L",   "1.36e4","1.36E4",    NA, "NA", "","NaN", NaN): 
    #' \cr positive or negative numbers with no more than one decimal c("-3","+4.4") OR
    #' \cr positive or negative integers (e.g., c("-42","4L","39L")) OR
    #' \cr positive or negative numbers in scientific notation c("1.36e4","1.36E4")
    #' \cr NA, or na.strings
    is.numeric.like <- function(x,naAsTrue=TRUE,na.strings=c('','.','NA','na','N/A','n/a','NaN','nan')){
        x = trimws(x,'both')
        x[x %in% na.strings] = NA
        # https://stackoverflow.com/a/21154566/2292993
        result = grepl("^[\\-\\+]?[0-9]+[\\.]?[0-9]*$|^[\\-\\+]?[0-9]+[L]?$|^[\\-\\+]?[0-9]+[\\.]?[0-9]*[eE][0-9]+$",x,perl=TRUE)
        if (naAsTrue) result = result | is.na(x)
        return((result))
    }
    

提交回复
热议问题