What do the %op% operators in mean? For example “%in%”?

前端 未结 5 1407
刺人心
刺人心 2020-11-28 22:37

I tried to do this simple search but couldn\'t find anything on the percent (%) symbol in R.

What does %in% mean in the following c

5条回答
  •  感情败类
    2020-11-28 23:10

    %in% is an operator used to find and subset multiple occurrences of the same name or value in a matrix or data frame.

    For example 1: subsetting with the same name

    set.seed(133)
    x <- runif(5)
    names(x) <- letters[1:5]
    x[c("a", "d")]
    #  a         d 
    #  0.5360112 0.4231022
    

    Now you change the name of "d" to "a"

     names(x)[4] <- "a"
    

    If you try to extract the similar names and its values using the previous subscript, it will not work. Notice the result, it does not have the elements of [1] and [4].

    x[c("a", "a")]
    
    #        a         a 
    #    0.5360112 0.5360112 
    

    So, you can extract the two "a"s from different position in a variable by using %in% binary operator.

    names(x) %in% "a"
    #  [1]  TRUE FALSE FALSE  TRUE FALSE
    
    #assign it to a variable called "vec"
     vec <- names(x) %in% "a"
    
    #extract the values of two "a"s
     x[vec]
     #         a         a 
     #  0.5360112 0.4231022 
    

    Example 2: Subsetting multiple values from a column Refer this site for an example

提交回复
热议问题