1

How to detect values ​​that are only composed of numbers? For example, I have this tibble:

example<- tibble(a=c("1234","abc","12c4","5678","3456","dce","456y"),
       b= seq(1:7))

example

 a         b
  <chr> <int>
1 1234      1
2 abc       2
3 12c4      3
4 5678      4
5 3456      5
6 dce       6
7 456y      7

and I want it to detect the values ​​1,4 and 5 in the b column, which are the values ​​exclusively composed of numbers. But I don't know how to do it. This doesn't work for me because it also detects mixed values :

str_detect(example$a, "[^a-z]")
[1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE

I need to return me this

"1234" "5678" "3456"

or this

TRUE FALSE FALSE TRUE TRUE FALSE FALSE

Ideally I would like to only work with column a, not column b.

Thanks!

juandmaz
  • 43
  • 6

1 Answers1

1

Use grepl:

grepl("^\\d+$", example$a)
[1]  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE

To get the matching values, just subset the column:

example$a[grepl("^\\d+$", example$a)]
[1] "1234" "5678" "3456"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360