The percent sign in R

后端 未结 2 1325
猫巷女王i
猫巷女王i 2021-02-06 04:05

I recently read some source code for a R package called \'pathifier\'. In the source code, it uses the percent sign.

if (0 %in% xs) {
si <- NULL
cat(file = l         


        
相关标签:
2条回答
  • 2021-02-06 04:42

    The in reserved word can only be used in for loops. The %in% function is different. As noted in the documentation at ?"%in%", is defined as:

    "%in%" <- function(x, table) match(x, table, nomatch = 0) > 0
    

    So, it is essentially match. In English, x %in% y returns a vector of logical of the same length as x, with TRUE every time the corresponding element of x exists at least once in y.

    The reason why there are % around it is to mark it as a "infix" operator. (I don't know if that is the exact term.)

    0 讨论(0)
  • 2021-02-06 04:45

    The useR is given the capacity to create new infix functions and the dispatch mechanism will recognize functions whose names begin and end with %. Say you wanted to make an infix operator that replicated a value n number of times:

     `%rep%` <- function(x,y) rep(x,y)
      10 %rep% 5
      # [1] 10 10 10 10 10
    

    Another example of doing such will be found on the help page for ?match which discusses %in% as well as demonstrates how to make an %w/o% infix operator. The section in the R Language Reference that describes this is 10.3.4: "Special operators".

    0 讨论(0)
提交回复
热议问题