July 25, 2019

R Pipe operator

Pipe operator, %>%, in R

x %>% f is equivalent to f(x)
x %>% f(y) is equivalent to f(x, y)
x %>% F(y, .) is equivalent to F(y, x)
x %>% fun(y, z = .) is equivalent to fun(y, z = x)
x %>% f(y = nrow(.), z = ncol(.)) is equivalent to f(x, y = nrow(x), z = ncol(x))

magrittr package %>% operator allows us to put "." where the data is supposed to go

x %>% add()
3 %>% sum(4)
pi %>% cos %>% sin == sin(cos(pi))
y %>%
  range() %>%
    abs()

:: Other Operators similar to Pipe Operator ::

%$% # Pipe with exposition of variables
iris %>%
  subset(Sepal.Length > mean(Sepal.Length)) %$%
  cor(Sepal.Length, Sepal.Width)
data.frame(z = rnorm(100)) %$%
  ts.plot(z)

rnorm(10000,mean=10,sd=1) %>>%
  sample(size=100,replace=FALSE) %>>%
  log %>>%
  diff %>>%
  plot(col="red",type="l")

%<>% # Compound assignment pipe operations
iris$Sepal.Length %<>% sqrt

library(dplyr)
data %.%
    melt(id.vars=c("treatment", "sex")) %.%
    group_by(sex, treatment, variable) %.%
    summarise(mean(value))
data %.% lm(formula=response1 ~ factor(sex)) %.% summary()

library(magrittr)
data %>% lm(response1 ~ factor(sex), .) %>% summary()

rnorm(100) %>%
  matrix(ncol = 2) %T>%
  plot() %>%
  str()

result <-
    looong_vector %>%
    lapply(
        one_action %,%
        another_action(requiring_x) %,%
        (lambda(. ~ finalizing_actions))
    )


Related aRticles: dplyr package in R   Data.Table package in R


No comments:

Post a Comment