Substitution of a vector with a condition (excluding NA)

vector1 = c(1,2,3,NA)
condition1 = (vector1 == 2)
vector1[condition1]
vector1[condition1==TRUE]

In the above code, condition 1 is “FALSE TRUE FALSE NA”, and the 3rd and 4th lines give me the result “2 NA”, which I did not expect.

I need elements whose values ​​are really "2", not including NA.

Can someone explain why R is designed to work this way? and how can I get the result that I want with a simple command?

+4
source share
4 answers

The subset vector[NA]will always be NAbecause the meaning is NAunknown, and therefore the result of the subset is also unknown. %in%returns FALSEfor NA, so it may be useful here.

vector1 = c(1,2,3,NA)
condition1 = (vector1 %in% 2)
vector1[condition1]
# [1] 2
+1
source

RStudio

?`[`

:

NAs

, NA NA , , , NULL . ( 00 .)

( lhs ) NA , . , rhs , , rhs 1 ( ). ( S , NA " , : Becker et al. 359. .)

+1

,

vector1 = c(1,2,3,NA)
condition1<-(vector1==2 & !is.na(vector1) )
condition1
# FALSE TRUE FALSE FALSE
vector1[condition1]
# 2

& true, True.

0

identical: " , . TRUE FALSE ". (. )

Since this does not compare elemental comparison, you can use it in sapply to compare each element in vector1 with 2. Ie:

condition1 = sapply(vector1, identical, y = 2)

which will give:

vector1[condition1]
[1] 2
0
source

Source: https://habr.com/ru/post/1696263/


All Articles