用 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")