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?
Trying ?max
, you'll see that it actually has a na.rm =
argument, set by default to FALSE
. (That's the common default for many other R functions, including sum()
, mean()
, etc.)
Setting na.rm=TRUE
does just what you're asking for:
d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)
If you do want to remove all of the NA
s, use this idiom instead:
d <- d[!is.na(d)]
A final note: Other functions (e.g. table()
, lm()
, and sort()
) have NA
-related arguments that use different names (and offer different options). So if NA
's cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's usually one already there.
The na.omit
function is what a lot of the regression routines use internally:
vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000
?max
shows you that there is an extra parameter na.rm
that you can set to TRUE
.
Apart from that, if you really want to remove the NA
s, just use something like:
myvec[!is.na(myvec)]
You can call max(vector, na.rm = TRUE)
. More generally, you can use the na.omit()
function.
Just in case someone new to R wants a simplified answer to the original question
How can I remove NA values from a vector?
Here it is:
Assume you have a vector foo
as follows:
foo = c(1:10, NA, 20:30)
running length(foo)
gives 22.
nona_foo = foo[!is.na(foo)]
length(nona_foo)
is 21, because the NA values have been removed.
Remember is.na(foo)
returns a boolean matrix, so indexing foo
with the opposite of this value will give you all the elements which are not NA.
Use discard
from purrr (works with lists and vectors).
discard(v, is.na)
The benefit is that it is easy to use pipes; alternatively use the built-in subsetting function [
:
v %>% discard(is.na)
v %>% `[`(!is.na(.))
来源:https://stackoverflow.com/questions/7706876/remove-na-values-from-a-vector