'Subsetting a vector with a logical condition

> x1=c(4,5,6,7,8)
> x1
[1] 4 5 6 7 8
> x2=x1[x1!=6]
> x2
[1] 4 5 7 8
> x3=x1[x1=6]
> x3
[1] NA

Why is x3 not 6? I don't understand.

r


Solution 1:[1]

<- and = are assignment operators. By using x1[x1=6], you are assigning the value of 6 to x1, not checking whether they match. Type in ?assignOps at the R prompt for more info. Use == instead.

x3 <- x1[x1==6]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brandon Bertelsen