功能序列

鉴于我们重复使用的一系列步骤,将它存储在函数中通常很方便。管道允许以可读格式保存这些功能,方法是启动带有点的序列,如下所示:

. %>% RHS

例如,假设我们有因子日期并想要提取年份:

library(magrittr) # needed to include the pipe operators
library(lubridate)
read_year <- . %>% as.character %>% as.Date %>% year

# Creating a dataset
df <- data.frame(now = "2015-11-11", before = "2012-01-01")
#          now     before
# 1 2015-11-11 2012-01-01

# Example 1: applying `read_year` to a single character-vector
df$now %>% read_year
# [1] 2015

# Example 2: applying `read_year` to all columns of `df`
df %>% lapply(read_year) %>% as.data.frame  # implicit `lapply(df, read_year)
#    now before
# 1 2015   2012

# Example 3: same as above using `mutate_all`
library(dplyr)
df %>% mutate_all(funs(read_year))
# if an older version of dplyr use `mutate_each`
#    now before
# 1 2015   2012

我们可以通过输入名称或使用 functions 来查看函数的组成:

read_year
# Functional sequence with the following components:
# 
#  1. as.character(.)
#  2. as.Date(.)
#  3. year(.)
# 
# Use 'functions' to extract the individual functions. 

我们还可以按顺序访问每个函数:

read_year[[2]]
# function (.) 
# as.Date(.)

通常,当清晰度比速度更重要时,这种方法可能是有用的。