Sometimes you want to select elements from a vector in a more advanced fashion. This is where the use of logical operators may come in handy.
The (logical) comparison operators known to R are:
- < for less than
- > for greater than
- <= for less than or equal to
- >= for greater than or equal to
- == for equal to each other全相等
- != not equal to each other不全相等
The nice thing about R is that you can use these comparison operators on vectors. For example, the statement c(4,5,6) > 5 returns: FALSE FALSE TRUE. In other words, you test for every element of the vector if the condition stated by the comparison operator is TRUE or FALSE.
Behind the scenes, R does an element-wise comparison of each element in the vector c(4,5,6) with the element 5. However, 5 is not a vector of lengththree. To solve this, R automatically replicates the value 5 to generate a vector of three elements, c(5, 5, 5) and then carries out the element-wise comparison.只要两组向量长度一样就可以做比较 如果长度不一样
Check which values in numeric_vector are larger than 10. Assign the result to the variable larger_than_ten.
print the variable larger_than_ten to the console.
注意辨析
numeric_vector <- c(1, 10, 49)
> numeric_vector==c(1,10,49)
[1] TRUE TRUE TRUE
> numeric_vector!=c(1,10,49)
[1] FALSE FALSE FALSE
> numeric_vector<=c(2,11)
[1] TRUE TRUE FALSE
Warning message:In numeric_vector <= c(2, 11) : longer object length is not a multiple of shorter object length
> numeric_vector==c(1,11,49)
[1] TRUE FALSE TRUE
> numeric_vector!=10
[1] TRUE FALSE TRUE