NovaX
NovaX

Reputation: 23

How to check data type of every single element of a vector in r?

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?

Upvotes: 1

Views: 580

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

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.

Upvotes: 2

Related Questions