Home > Enterprise >  Where is %% used in R?
Where is %% used in R?

Time:08-25

I am beginner at R and learning about loops, I came across these two examples:

v <- LETTERS[1:4]
for ( i in v) {
  print(i)
}
x <- c("Hardwork","is","the","key","of","success")  
y="is"
if(y %in% x) {    
  print("key is found")  
} else {  
  print("key is not found")  
} 

Here, I am not able to understand why we used %in% in the second example and "in" in the first example. I tried to use them the other way around but I got an error. How can this rule of using %in% be generalised?

CodePudding user response:

The '%' signs denote an infix operator

This is explained most quickly with an example. Most functions in R do something to something else. So f(x) is doing function f() to object x.

Infix operators are also functions, but they do something to two things. So x %in% y does %in% to x and y.

You can easily make your own infix operators, like so:

x <- c(1,2,3)
y <- c(5,2,9,10)

## get the max value of each vector at each index
`%is_longer_than%` <- function(x,y){
  if(length(x) > length(y)) TRUE
  else FALSE
}

x %is_longer_than% y
#> [1] FALSE

y %is_longer_than% x
#> [1] TRUE

Created on 2022-08-24 by the reprex package (v2.0.1)

You can actually see that %in% is just a function in R by running `%in%` in the console:

`%in%`
#> function (x, table) 
#> match(x, table, nomatch = 0L) > 0L
#> <bytecode: 0x00000226009335c0>
#> <environment: namespace:base>

Created on 2022-08-24 by the reprex package (v2.0.1)

So x %in% y is equivalent to match(x, y, nomatch = 0L)

in versus %in%

in and %in% are two completely different things. The '%' signs don't do something to in, they're just different functions with similar names. in is a reserved word in R, which does very secret things in C . It's similar to other reserved words like for and <.

  •  Tags:  
  • r
  • Related