R函数内修改变量 [英] modify variable within R function
问题描述
如何修改一个参数传递给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。
推荐答案
有办法为@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屋!