Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in R Programming by (7.3k points)

I have a huge vector which has a couple of NA values, and I'm trying to find the max value in that vector (the vector is all numbers), but I can't do this because of the NA values.

How can I remove the NA values so that I can compute the max?

2 Answers

+1 vote
by
edited

To remove NA’s from a vector use the following code:

Vec <- Vec[!is.na(Vec)]

For example:

Vec <- c(1, 100, NA, 10,NA,5,6,7,8,9,4,3,5,NA)

Vec <- Vec[!is.na(Vec)]

Vec

 [1]   1 100  10   5   6   7   8   9   4   3   5

You can also use the na.rm  argument inside the max function to find the maximum number.

For example:

Vec <- c(1, 100, NA, 10,NA,5,6,7,8,9,4,3,5,NA)

max(Vec, na.rm = TRUE)

Output:

[1] 100

If you want to explore more in R programming then watch this R programming tutorial for beginner:

+1 vote
by (32.3k points)

I think you can use na.omit function. A lot of the regression routines use it internally:

vec <- 1:1000

vec[runif(200, 1, 1000)] <- NA

max(vec)

#[1] NA

max( na.omit(vec) )

#[1] 1000

Related questions

Browse Categories

...