从向量中删除NA值 [英] Remove NA values from a vector
问题描述
我有一个巨大的向量,它具有几个NA
值,并且我试图在该向量中找到最大值(向量是所有数字),但是由于NA
值.
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.
如何删除NA
值,以便可以计算最大值?
How can I remove the NA
values so that I can compute the max?
推荐答案
尝试?max
时,您会看到它实际上有一个na.rm =
参数,默认情况下设置为FALSE
. (这是许多其他R函数的常见默认值,包括sum()
,mean()
等)
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.)
设置na.rm=TRUE
可以满足您的要求:
Setting na.rm=TRUE
does just what you're asking for:
d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)
如果确实要删除所有NA
,请改用以下惯用法:
If you do want to remove all of the NA
s, use this idiom instead:
d <- d[!is.na(d)]
最后的注释:其他函数(例如table()
,lm()
和sort()
)具有与NA
相关的参数,这些参数使用不同的名称(并提供不同的选项).因此,如果NA
导致您在函数调用中遇到问题,则值得检查函数参数中的内置解决方案.我发现已经有一个通常了.
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.
这篇关于从向量中删除NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!