用 T 建立副作用
R 中的某些函式產生副作用(即儲存,列印,繪圖等)並且不總是返回有意義或期望的值。
%T>%
(tee operator)允許你將值轉換為副作用生成函式,同時保持原始 lhs
值不變。換句話說:tee 運算子就像%>%
一樣工作,除了返回值是 lhs
本身,而不是 rhs
函式/表示式的結果。
示例:建立,管道,寫入和返回物件。如果在本例中使用%>%
代替%T>%
,則變數 all_letters
將包含 NULL
而不是 sort 物件的值。
all_letters <- c(letters, LETTERS) %>%
sort %T>%
write.csv(file = "all_letters.csv")
read.csv("all_letters.csv") %>% head()
# x
# 1 a
# 2 A
# 3 b
# 4 B
# 5 c
# 6 C
警告:將未命名的物件管道傳輸到 save()
將在使用 load()
載入到工作區時生成名為 .
的物件。但是,可以使用輔助函式進行解決方法(也可以作為匿名函式內聯編寫)。
all_letters <- c(letters, LETTERS) %>%
sort %T>%
save(file = "all_letters.RData")
load("all_letters.RData", e <- new.env())
get("all_letters", envir = e)
# Error in get("all_letters", envir = e) : object 'all_letters' not found
get(".", envir = e)
# [1] "a" "A" "b" "B" "c" "C" "d" "D" "e" "E" "f" "F" "g" "G" "h" "H" "i" "I" "j" "J"
# [21] "k" "K" "l" "L" "m" "M" "n" "N" "o" "O" "p" "P" "q" "Q" "r" "R" "s" "S" "t" "T"
# [41] "u" "U" "v" "V" "w" "W" "x" "X" "y" "Y" "z" "Z"
# Work-around
save2 <- function(. = ., name, file = stop("'file' must be specified")) {
assign(name, .)
call_save <- call("save", ... = name, file = file)
eval(call_save)
}
all_letters <- c(letters, LETTERS) %>%
sort %T>%
save2("all_letters", "all_letters.RData")