Check if row contains ONLY NUMBERS or ONLY CHARACTERS (R)
I have these three lines:
letters <- "abc"
numbers <- "123"
mix <- "b1dd"
How can I check which of these lines contains ONLY LETTERS or ONLY NUMBERS (in R)?
letters
must be TRUE only in LETTERS
numbers
must be TRUE in checking NUMBERS ONLY
mix
must be FALSE in any situation
I've tried several approaches now, but none of them really worked for me :(
For example, if I use
grepl("[A-Za-z]", letters)
This works well for letters
, but it also works for mix
which I don't want.
Thank you in advance.
+5
source to share
2 answers
# Check that it doesn't match any non-letter
letters_only <- function(x) !grepl("[^A-Za-z]", x)
# Check that it doesn't match any non-number
numbers_only <- function(x) !grepl("\\D", x)
letters <- "abc"
numbers <- "123"
mix <- "b1dd"
letters_only(letters)
## [1] TRUE
letters_only(numbers)
## [1] FALSE
letters_only(mix)
## [1] FALSE
numbers_only(letters)
## [1] FALSE
numbers_only(numbers)
## [1] TRUE
numbers_only(mix)
## [1] FALSE
+12
source to share