Back
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?
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
Vec <- c(1, 100, NA, 10,NA,5,6,7,8,9,4,3,5,NA)
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.
Vec <- c(1, 100, NA, 10,NA,5,6,7,8,9,4,3,5,NA)max(Vec, na.rm = TRUE)Output:[1] 100
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:
I think you can use na.omit function. A lot of the regression routines use it internally:
vec <- 1:1000vec[runif(200, 1, 1000)] <- NAmax(vec)#[1] NAmax( na.omit(vec) )#[1] 1000
vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000
31k questions
32.8k answers
501 comments
693 users