how to determine if a character vector is a valid numeric or integer vector

前端 未结 6 1918
醉酒成梦
醉酒成梦 2021-01-04 01:38

I am trying to turn a nested list structure into a dataframe. The list looks similar to the following (it is serialized data from parsed JSON read in using the httr package)

6条回答
  •  臣服心动
    2021-01-04 01:59

    When NAs are included @josliber's function won't work (though it answers the question well for the sample data). @Amy M's function should work but requires loading Hmisc package.

    What about something like this:

    can.be.numeric <- function(x) {
        stopifnot(is.atomic(x) || is.list(x)) # check if x is a vector
        numNAs <- sum(is.na(x))
        numNAs_new <- suppressWarnings(sum(is.na(as.numeric(x))))
        return(numNAs_new == numNAs)
    }
    

    It counts NAs in input vector and NAs in the output of as.numeric() and returns TRUE if the vector can be "safely" converted to numeric (i.e. without adding any additional NA values).

提交回复
热议问题