3

I need a function like this:

note<-function(object,text=""){attributes(object)[4]<-text}  

eg: note(xxx,"yyyy")

in which I try to set to the value "yyyy" the fourth attribute of xxx object (in the global env). As it is, the function (as expected) doesn't work because it modifies the value in the
function env.
Any suggestion?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user1453488
  • 441
  • 1
  • 4
  • 4

2 Answers2

4

You could make the function return the object itself, so it can be re-assigned:

note <- function(object, text = "") {
    attributes(object)[4] <- text
    return(object)
}

xxx <- note(xxx, "yyyy")
flodel
  • 87,577
  • 21
  • 185
  • 223
  • this way is not useful, because I should reassign manually, but thanks – user1453488 Sep 03 '12 at 12:02
  • 6
    In R, functions are not expected to modify their arguments, so yes, it is best to reassign manually. – Gabor Csardi Sep 03 '12 at 12:12
  • 1
    You'll find more info if you search "pass by value" versus "pass by reference". Because R uses "pass by value", what I suggested is the easier and recommended way. However, it is not impossible to use "pass by reference", though difficult. This might help: http://stackoverflow.com/questions/2603184/r-pass-by-reference – flodel Sep 03 '12 at 12:26
0

Here the solution ( found trying the flodel suggestion ) :

note<-function(object,text=""){
 object2<-object
 attributes(object2)[4]<-text
 assign(deparse(substitute(object)),object2,envir=.GlobalEnv)
}

thanks to all

user1453488
  • 441
  • 1
  • 4
  • 4
  • I wouldn't call that "the" solution. Having functions interact with variables outside of their environment is highly frowned upon because dangerous (e.g. search "why is it bad to use global variables"). Again, best practice recommends that the function returns a modified object so it can be reassigned. – flodel Oct 07 '12 at 18:00