功能序列
鑑於我們重複使用的一系列步驟,將它儲存在函式中通常很方便。管道允許以可讀格式儲存這些功能,方法是啟動帶有點的序列,如下所示:
. %>% 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(.)
通常,當清晰度比速度更重要時,這種方法可能是有用的。