I am coercing a input from readLines()
which I understand will take any input, character or numeric, and capture it as a character value. I then want to convert the input to a numeric value using as.numeric()
.
I then want to use a validation test such as is.numeric()
to check that user has input 5 vs a character string as "five" with the assertthat package.
However when I coerce a character vector (eg. "five") to as.numeric()
it will produce a NA output. when you test an NA output with is.numeric()
it will produce a TRUE defeating the whole purpose
How can I validate that a user input a numeric value given that readLines()
converts everything to a character vector?
#both of the below produce TRUE
is.numeric(as.numeric("five"))
is.numeric(as.numeric(5))
I believe you can use !is.na
to test the result of as.numeric
. If it failed to convert to valid numeral values, as.numeric
returns NA
.
!is.na(as.numeric("five"))
#> Warning: NAs introduced by coercion
#> [1] FALSE
!is.na(as.numeric("5"))
#> [1] TRUE
!is.na(as.numeric(5))
#> [1] TRUE
Or use the regex ^[0-9]+$
to see if the whole input is made up entirely of integers (for testing integers only, not for testing floating point numbers).
grepl("^[0-9]+$", "five")
#> [1] FALSE
grepl("^[0-9]+$", "fi55ve")
#> [1] FALSE
grepl("^[0-9]+$", "356236345")
#> [1] TRUE
grepl("^[0-9]+$", 5235)
#> [1] TRUE
Created on 2023-09-15 with reprex v2.0.2