如何模拟通过引用传递的参数 [英] how to emulate parameters passed by reference

查看:71
本文介绍了如何模拟通过引用传递的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有办法吗?
注意:问题不在于做这样的事情是否正确、好或明智.
问题是是否有办法,所以如果你的答案是你为什么想这么做?"R 使用了你想要的函数,你想要的函数曾经被称为过程,而好的 R 用法/风格不会......",你能解释得更好吗......提供一些代码"不要回答.

Is there a way?
NB: the question is not whether it is right, good or sensible to do such a thing.
The question is if there is a way, so if your answer would be "why would you want to do that?" "R uses functions what you want was once called procedure and good R usage/style does not ...", "could you explain better... provide some code" do NOT answer.

我做了一个快速尝试,不起作用最终起作用了,使用环境,或多或少:

I did a quick try, that did not work eventually worked, using environments, more or less:

function(mydf) {
  varName <- deparse(substitute(mydf))
  ...
  assign(varName,mydf,envir=parent.frame(n = 1))
}  

推荐答案

1) 将函数体包裹在 eval.parent(substitute({...})) 像这样:

1) Wrap the function body in eval.parent(substitute({...})) like this:

f <- function(x) eval.parent(substitute({
  x <- x + 1
}))

mydf <- data.frame(z = 1)
f(mydf)
mydf
##   z
## 1 2

另请参阅 gtools 和 wrapr 包中的 defmacro 函数.

Also see the defmacro function in gtools and the wrapr package.

2) 另一种可能是使用替换函数:

2) An alternative might be to use a replacement function:

"incr<-" <- function(x, value) {
      x + value
}

mydf <- data.frame(z = 1)
incr(mydf) <- 1
mydf
##   z
## 1 2

3) 或者只是覆盖输入:

f2 <- function(x) x + 1
mydf <- data.frame(z = 1)
mydf <- f2(mydf)
mydf
##   z
## 1 2

如果问题是有多个输出,则使用 gsubfn 包中的 list.这用于带有方括号的赋值的左侧,如图所示.见help(list, gsubfn)

If the problem is that there are multiple outputs then use list in the gsubfn package. This is used on the left hand side of an assignment with square brackets as shown. See help(list, gsubfn)

library(gsubfn)
f3 <- function(x, y) list(x + 1, y + 2)
mydf <- mydf2 <- data.frame(z = 1)
list[mydf, mydf2] <- f3(mydf, mydf2)
mydf
##   z
## 1 2
mydf2
##   z
## 1 3

这篇关于如何模拟通过引用传递的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆