In R, say I have a vector
myvec <- c(123, a33, 164, 9234, 1)
I want to check if the vector values are 3-digit numbers, so that I get the output
TRUE FALSE TRUE FALSE FALSE
Anyone know how to do this?
CodePudding user response:
You can use regex to find a specific expression.
The following code using grepl function will test for each values of vector x, the pattern starting ^ and ending $ with 3 {3} digits [0-9].
x <- c(123, 'a33', 164, 9234, 1)
grepl(pattern="^[0-9]{3}$", x=x)
CodePudding user response:
Alternatively, you could use parse_number() to extract the numbers and then count nchar(). This additional step is necessary if you have the case like the last entry "b345".
x <- c(123, 'a33', 164, 9234, 1, 'b345')
nchar(readr::parse_number(x)) == 3
Output
[1] TRUE FALSE TRUE FALSE FALSE TRUE
