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

前端 未结 6 1969
醉酒成梦
醉酒成梦 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 02:04

    As discussed here, checking if as.numeric returns NA values is a simple approach to checking if a character string contains numeric data. Now you can do something like:

    myDF2 <- lapply(myDF, function(col) {
      if (suppressWarnings(all(!is.na(as.numeric(as.character(col)))))) {
        as.numeric(as.character(col))
      } else {
        col
      }
    })
    str(myDF2)
    # List of 3
    #  $ w  : num [1:2] 1 2
    #  $ x.y: num [1:2] 0.1 0.2
    #  $ x.z: Factor w/ 2 levels "cat","dog": 1 2
    

提交回复
热议问题