在 R 函数中修改变量 [英] modify variable within R function

查看:36
本文介绍了在 R 函数中修改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改传递给 R 中函数的参数?在 C++ 中,这将通过引用传递.

How do I modify an argument being passed to a function in R? In C++ this would be pass by reference.

g=4
abc <- function(x) {x<-5}
abc(g)

我希望将 g 设置为 5.

I would like g to be set to 5.

推荐答案

@Dason 展示了一些方法,但实际上 - 你不应该

There are ways as @Dason showed, but really - you shouldn't!

R 的整个范式是按值传递".@Rory 刚刚发布了处理它的正常方法 - 只需返回修改后的值...

The whole paradigm of R is to "pass by value". @Rory just posted the normal way to handle it - just return the modified value...

环境通常是 R 中唯一可以通过引用传递的对象.

Environments are typically the only objects that can be passed by reference in R.

但是最近 R 中添加了称为引用类的新对象(它们使用环境).他们可以修改他们的值(但以一种受控的方式).如果你真的觉得有必要,你可能想考虑使用它们......

But lately new objects called reference classes have been added to R (they use environments). They can modify their values (but in a controlled way). You might want to look into using them if you really feel the need...

这篇关于在 R 函数中修改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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