基本使用和链接

管道运算符%>%用于将参数插入到函数中。它不是该语言的基本功能,只能在附加提供它的包之后使用,例如 magrittr。管道运算符采用管道的左侧(LHS)并将其用作管道右侧(RHS)上的功能的第一个参数。例如:

library(magrittr)

1:10 %>% mean
# [1] 5.5

# is equivalent to
mean(1:10)
# [1] 5.5

管道可用于替换一系列函数调用。多个管道允许我们从左到右读取和写入序列,而不是从内到外读取和写入序列。例如,假设我们将 years 定义为一个因子,但希望将其转换为数字。为防止可能的信息丢失,我们首先转换为字符,然后转换为数字:

years <- factor(2008:2012)

# nesting
as.numeric(as.character(years))

# piping
years %>% as.character %>% as.numeric

如果我们不希望 LHS(左手侧)用作 RHS(右手侧) 的第一个参数,则有一些解决方法,例如命名参数或使用 . 来指示管道输入的位置。

# example with grepl
# its syntax:
# grepl(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

# note that the `substring` result is the *2nd* argument of grepl
grepl("Wo", substring("Hello World", 7, 11))

# piping while naming other arguments
"Hello World" %>% substring(7, 11) %>% grepl(pattern = "Wo")

# piping with .
"Hello World" %>% substring(7, 11) %>% grepl("Wo", .)

# piping with . and curly braces
"Hello World" %>% substring(7, 11) %>% { c(paste('Hi', .)) }
#[1] "Hi World"

#using LHS multiple times in argument with curly braces and .
"Hello World" %>% substring(7, 11) %>% { c(paste(. ,'Hi', .)) }
#[1] "World Hi World"