如果我們決定使用subset
功能,那麼我們就需要注意:
For ordinary vectors, the result is simply ‘x[subset & !is.na(subset)]’.
所以唯一的非NA值將被保留。
如果你想保持NA
案件,使用邏輯或條件,讓R不掉NA
案件:
subset(df1, Height < 40 | is.na(Height))
# or `df1[df1$Height < 40 | is.na(df1$Height), ]`
不要直接使用(即將解釋):
df2 <- df1[df1$Height < 40, ]
實施例
df1 <- data.frame(Height = c(NA, 2, 4, NA, 50, 60), y = 1:6)
subset(df1, Height < 40 | is.na(Height))
# Height y
#1 NA 1
#2 2 2
#3 4 3
#4 NA 4
df1[df1$Height < 40, ]
# Height y
#1 NA NA
#2 2 2
#3 4 3
#4 NA NA
後者失敗的原因是NA
索引NA
。考慮這個簡單的例子用向量:
x <- 1:4
ind <- c(NA, TRUE, NA, FALSE)
x[ind]
# [1] NA 2 NA
我們需要以某種方式與TRUE
替換那些NA
。最直接的方法是添加另一個「或」條件is.na(ind)
:
x[ind | is.na(ind)]
# [1] 1 2 3
這也正是將您的情況發生什麼。如果您的Height
包含NA
,那麼邏輯運算Height < 40
結束了TRUE
/FALSE
/NA
的混合,因此我們需要用TRUE
替代NA
,如上所述。
或者,我們可以使用'子集(DF1,高度<40 | is.na(高度))' – Zach
爲了完整起見,從'dplyr'包類似的選項'filter(df1,Height <40 | is.na(Height))' –