以最少的输入将函数应用于 R 中的最后结果
Applying a function to the last result in R with minimal typing
在 Twitter 我问了以下问题:
In RStudio, is there an easy way to pipe the last result stored in
.Last.value
into a function. Say I did:
tbl <- CreateTable(x)
.
I now want to do View(tbl)
but with less typing. Just type
.View
or something. Is that possible? #rstats #rstudio
是否有通用的方法来做到这一点?
这里有一些方法,这些都是奇怪的东西,所以我希望你能保留它以供交互使用,不要在你的 RProfile 中放任何东西,也不要使用那些共享代码:)。
1 - 为 .
创建绑定
.
将是 .Last.Value
的快捷方式,节省了大部分输入。
magrittr 管道和功能序列仍然有效,purrr lambdas 也将如此。
makeActiveBinding(".", function() .Last.value, .GlobalEnv)
4
sqrt(.) # 2
如果您的键盘上有 µ
、λ
或其他兼容的特殊字符,最好改用它。
2 - 黑客攻击 print.function
我们可以破解 print.function
以便它在最后一个值上运行该函数。
这里我不能使用.Last.value
因为它是函数本身的值,所以我需要重新执行之前的调用,所以在某些情况下可能会很慢。
print.function <- function(x){
tf <- tempfile()
savehistory(tf)
last_calls <- parse(text=tail(readLines(tf),2))
if(as.list(last_calls[[2]])[[1]] == quote(print))
base:::print.function(x) else print(x(eval.parent(last_calls[[1]])))
}
4
sqrt # 2
4
print(sqrt) # the actual definition
3 - 使用包疑问
我们可以构建一个可疑的运算符,它将使用 .Last.value
:
# remotes::install_github("moodymudskipper/doubt")
library(doubt)
`?+{fun}` <- function(fun){ fun(.Last.value)}
4
?+sqrt # 2
4 - 给你关心的函数一个class
并为一元运算符定义一个方法(+
、-
和 !
都可以):
class(sqrt) <- class(summary) <- class(View) <- "magic_function"
`+.magic_function` <- function(fun){ fun(.Last.value)}
4
+sqrt # 2
在 Twitter 我问了以下问题:
In RStudio, is there an easy way to pipe the last result stored in
.Last.value
into a function. Say I did:
tbl <- CreateTable(x)
.I now want to do
View(tbl)
but with less typing. Just type
.View
or something. Is that possible? #rstats #rstudio
是否有通用的方法来做到这一点?
这里有一些方法,这些都是奇怪的东西,所以我希望你能保留它以供交互使用,不要在你的 RProfile 中放任何东西,也不要使用那些共享代码:)。
1 - 为 .
.
将是 .Last.Value
的快捷方式,节省了大部分输入。
magrittr 管道和功能序列仍然有效,purrr lambdas 也将如此。
makeActiveBinding(".", function() .Last.value, .GlobalEnv)
4
sqrt(.) # 2
如果您的键盘上有 µ
、λ
或其他兼容的特殊字符,最好改用它。
2 - 黑客攻击 print.function
我们可以破解 print.function
以便它在最后一个值上运行该函数。
这里我不能使用.Last.value
因为它是函数本身的值,所以我需要重新执行之前的调用,所以在某些情况下可能会很慢。
print.function <- function(x){
tf <- tempfile()
savehistory(tf)
last_calls <- parse(text=tail(readLines(tf),2))
if(as.list(last_calls[[2]])[[1]] == quote(print))
base:::print.function(x) else print(x(eval.parent(last_calls[[1]])))
}
4
sqrt # 2
4
print(sqrt) # the actual definition
3 - 使用包疑问
我们可以构建一个可疑的运算符,它将使用 .Last.value
:
# remotes::install_github("moodymudskipper/doubt")
library(doubt)
`?+{fun}` <- function(fun){ fun(.Last.value)}
4
?+sqrt # 2
4 - 给你关心的函数一个class
并为一元运算符定义一个方法(+
、-
和 !
都可以):
class(sqrt) <- class(summary) <- class(View) <- "magic_function"
`+.magic_function` <- function(fun){ fun(.Last.value)}
4
+sqrt # 2