What does the function of %% and% any% in r?

3

I have been reading the documentation of R and in the document Arithmetic{base} , Arithmetic Operators I came across the %% that says to have the mod function, which I assumed was the modulo function, but when I executed it seemed to function rep() , so I did not understand the logic. I ran into %<% or %<% that seemed to receive a function and execute them differently than normal, ie within () .

    
asked by anonymous 19.06.2018 / 22:04

1 answer

5

The %% function is the modulo function, in the sense of modular arithmetic. Note that the result of 17 %% 3 is 2 , because 17 = 3*5 + 2 . Also, note that the result of 17 %/% 3 is 5, completing the result of %% . Therefore, the %% and %/% functions function to perform the integer division within the R.

The %>% function, also called pipe , serves to chain commands. Perhaps the best package is dplyr . Imagine that I want to get the iris dataset and perform some operations on it:

head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Suppose I want to select only columns Petal.Length and Petal.Width , whose Sepal.Length is greater than 5, but only the species setosa. I can do this in R so:

subset(iris[iris$Sepal.Length > 5, c(3, 4, 5)], Species=="setosa")

Note how the syntax is complicated. Although they do the right job, subset functions and index searches by R are not very user friendly. See how everything gets easier with pipe :

iris %>%
  filter(Sepal.Length > 5) %>%
  filter(Species == "setosa") %>%
  select(Petal.Length, Petal.Width, Species)

With the pipe I am chaining commands. I get the result of iris set and step to filtering according to Sepal.Length > 5 ; then I get this result and step into the Species == "setosa" filtering; and finally I select only the columns that interest me.

It's much cleaner to write the codes and much easier to read later, either your own code written in the past or someone else's code.

Curiosity: The %>% function appeared in a package named magrittr , which was previously called plumbr . The package has name test in honor of René Magritte, Belgian painter who produced the work below:

"This is not a pipe"

The pipe command appeared in another programming language called F #. When it came to the R, the author of the plumbr package decided to make a big pun, joining the pipe concept in pipe and honoring a famous painter. Source with more details of this story .

    
19.06.2018 / 23:23