I want to check if all elements are numeric in the vector y
y <- c(8.2, 2.5, 4.3, 3.2, 4.9, 7.0, NA, 5.3, 7.7, NA, 8.1, 3.0, 6.4, 6.5)
is.numeric(y)
is.numeric(y) gives me TRUE although there are NAs in the vector. Is there a way to get the data type of every single element?
CodePudding user response:
Atomic vectors can only have a single data type. So if is.numeric(your_vector)
is TRUE
, then all elements of the vector are numeric.
There are different types of NA
, e.g., NA_character_
which is character
class, NA_real_
which is numeric
class, etc. See the ?NA
help page for more detail. But since all elements of a vector must be the same class, you don't have to check the type of NA
values in a numeric vector, you know they are numeric.
A list
is a special kind of vector that can hold different classes.
You can test for any NA
values in the vector with anyNA()
. Or use is.na()
to test each individual element.
CodePudding user response:
If you want to check if your vector is.numeric
and without NAs, you can do:
is.numeric(y) & all(complete.cases(y))
#[1] FALSE