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

前端 未结 6 1947
醉酒成梦
醉酒成梦 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:55

    If you just want to convert all-numeric vectors that have been erroneously classed as character when they were read in, you can also use the function all.is.numeric from the Hmisc package:

    myDF2 <- lapply(myDF, Hmisc::all.is.numeric, what = "vector", extras = NA)
    

    Choosing what = "vector" will convert the vector to numeric if it only contains numbers. NAs or other types of missing values will prevent conversion unless they are specified in the extras argument as above.

    Note however that if applied to a whole data.frame containing Date or POSIXct vectors, these will also be converted to numeric. To prevent this you can wrap it in a function as below:

    catchNumeric <- function(dtcol) {
      require(Hmisc)
      if (is.character(dtcol)) {
        dtcol1 = all.is.numeric(dtcol, what = "vector", extras = NA)
      } else {
        dtcol1 = dtcol
      }
      return(dtcol1)
    }
    

    Then apply to your data.frame:

    myDF2 <- lapply(myDF, catchNumeric)
    

提交回复
热议问题