1

Is there an easy way to check if a vector only contains positive single-digit numbers (i.e. only numbers from 0 to 9)?

user2884679
  • 129
  • 4
  • 9

2 Answers2

4
fun <- function(vec) all(vec >= 0 & vec <= 9 & vec%%1==0)
vec <- 0:9
fun(vec)
#TRUE
vec2 <- 5:14
fun(vec2)
#FALSE
alexwhan
  • 15,636
  • 5
  • 52
  • 66
  • I just noticed the "Note" in `?is.integer`, where it says that `is.wholenumber` should be used instead. And gives this example `is.integer(1)` that returns `FALSE`!. – alexis_laz Nov 13 '13 at 11:27
  • 1
    @alexis_laz `is.wholenumber` is a function that only exists in the example. Just wanted to make that clear to anyone who expects it to exist in the `base` package. – Carl Witthoft Nov 13 '13 at 12:35
  • 1
    @alexis_laz good catch, edited with test from http://stackoverflow.com/questions/3476782/how-to-check-if-the-number-is-integer – alexwhan Nov 13 '13 at 13:43
2

Another way is to use nchar that sees characters and not numbers, so a number with nchar > 1 night be decimal, negative single-digit, double-digit, etc.

all(nchar(0:9) == 1)
#[1] TRUE
all(nchar(0:12) == 1) #double digits
#[1] FALSE
all(nchar(-5:1) == 1)  #negative
#[1] FALSE
all(nchar(runif(5, 0, 9)) == 1) #decimal between 0 and 9
#[1] FALSE
nchar(1.00) #!
#[1] 1
alexis_laz
  • 12,884
  • 4
  • 27
  • 37
  • Interesting: `nchar(1.0) #returns 1` . My only concern is that this is not explicitly documented, which suggests that the way `nchar` coerces floats could change in the future. Right now it appears to do the same as `as.character(1.0) # 1` – Carl Witthoft Nov 13 '13 at 12:40
  • @CarlWitthoft: I didn't expect that either. I looked at [`do_nchar`](http://svn.r-project.org/R/trunk/src/main/character.c) and I guessed this line is responsible for this behaviour: `x = coerceVector(CAR(args), STRSXP)` that turns the first argument of `nchar` to character. If so, I guess then, it might continue to behave the same because it looks vital in the code? I've no idea – alexis_laz Nov 13 '13 at 12:55