在R中通过引用调用(使用函数来修改对象) [英] Call by reference in R (using function to modify an object)

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

问题描述

我只是在R中弄湿了自己的脚,并且很惊讶地看到一个函数不能修改一个对象,至少它看起来是默认的。例如,我写了一个函数,只是在表格中的一个标签上粘上一个星号;它在函数内部工作,但是表本身没有改变。 (我主要来自Ruby)



那么,使用函数来改变R中的对象的正常的,可接受的方式是什么?如何将星号添加到表格标题中?




  • 替换整个对象: myTable = title .asterisk(myTable)


  • 使用解决方法通过引用进行调用(例如, TszKin Julian在R 中引用参考文献


  • 使用一个函数以外的结构?一个对象方法?



解决方案

这两个范例正在取代整个对象,如您所指出的那样,或者编写'替换'函数,如

 `updt< -`<  -  function(x,...,value){
## x是要操作的对象,赋值对象
x $ lbl < - paste0(x $ lbl,value)
x
}

与< / p>

 > d < -  data.frame(x = 1:5,lbl = letters [1:5]) 
> d
x lbl
1 1 a
2 2 b
3 3 c
> updt(d)< - *
> d
x lbl
1 1 a *
2 2 b *
3 3 c *

例如, $ < - - 就地更新 $ 。 这里是一个相关的问题。可以将替换函数想象为语法糖用于

pre $ lt; code> updt1< - function(x,...,value){
x $ lbl< - paste0(x $ lbl,value)
x
}
d< - updt1(d,value =*)

但在我看来,标签'语法糖'并没有真正公正地涉及到所涉及的中心范式。它可以实现方便的就地更新,这与R通常保持的不断变化的错觉不同,它实际上是更新对象的'R'方式(而不是使用?ReferenceClasses ,例如,它具有更多其他语言的感觉,但会令预期更改时复制语义的R用户感到惊讶。)

I'm just getting my feet wet in R and was surprised to see that a function doesn't modify an object, at least it seems that's the default. For example, I wrote a function just to stick an asterisk on one label in a table; it works inside the function but the table itself is not changed. (I'm coming mainly from Ruby)

So, what is the normal, accepted way to use functions to change objects in R? How would I add an asterisk to the table title?

  • Replace the whole object: myTable = title.asterisk(myTable)

  • Use a work-around to call by reference (as described, for example, in Call by reference in R by TszKin Julian?

  • Use some structure other than a function? An object method?

解决方案

The two paradigms are replacing the whole object, as you indicate, or writing 'replacement' functions such as

`updt<-` <- function(x, ..., value) {
    ## x is the object to be manipulated, value the object to be assigned
    x$lbl <- paste0(x$lbl, value)
    x
}

with

> d <- data.frame(x=1:5, lbl=letters[1:5])
> d
  x lbl
1 1   a
2 2   b
3 3   c
> updt(d) <- "*"
> d
  x lbl
1 1  a*
2 2  b*
3 3  c*

This is the behavior of, for instance, $<- -- in-place update the element accessed by $. Here is a related question. One could think of replacement functions as syntactic sugar for

updt1 <- function(x, ..., value) {
    x$lbl <- paste0(x$lbl, value)
    x
}
d <- updt1(d, value="*")

but the label 'syntactic sugar' doesn't really do justice, in my mind, to the central paradigm that is involved. It is enabling convenient in-place updates, which is different from the copy-on-change illusion that R usually maintains, and it is really the 'R' way of updating objects (rather than using ?ReferenceClasses, for instance, which have more of the feel of other languages but will surprise R users expecting copy-on-change semantics).

这篇关于在R中通过引用调用(使用函数来修改对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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