[R] beginner programming question

Tony Plate tplate at blackmesacapital.com
Thu Dec 18 00:42:25 CET 2003


Thanks.  As a follow-up question, is it considered acceptable programming 
practice for "<-" functions to modify their x argument?

-- Tony Plate

At Thursday 12:23 AM 12/18/2003 +0100, Peter Dalgaard wrote:
>Tony Plate <tplate at blackmesacapital.com> writes:
>
> >  > xx <- rbind("colnames<-"(x[,c("rel1","age0","age1","sex0","sex1")], nn),
> > +  "colnames<-"(x[,c("rel2","age0","age2","sex0","sex2")], nn),
> > +  "colnames<-"(x[,c("rel3","age0","age3","sex0","sex3")], nn))
>....
> > PS.  To advanced R users: Is the above usage of the "colnames<-"
> > function within an expression regarded as acceptable or as undesirable
> > programming style? -- I've rarely seen it used, but it can be quite
> > useful.
>
>I wouldn't be happy with it. These assignment functions can do things
>that really only makes sense when used in the context of foo(x) <-
>bar. It is true that if you define "foo<-" as an ordinary R function
>of x and bar that returns the modified x, then foo(x)<-bar will work,
>but the converse might not be true. The programmer may have done
>things for the sake of efficiency that makes "foo<-" behave in
>non-standard ways. In particular it might destructively modify its
>x argument.
>
>In the above case, the modified argument is a temporary, so it is
>likely to be safe, but as a programming paradigm it might spring some
>nasty surprises in the face of the unsuspecting user. So I'd prefer
>something like
>
>xx <- do.call("rbind",
>          lapply(list(x[,c("rel1","age0","age1","sex0","sex1")],
>                      x[,c("rel2","age0","age2","sex0","sex2")],
>                      x[,c("rel3","age0","age3","sex0","sex3")]),
>                 function(x) {colnames(x) <- nn; x})
>
>--
>    O__  ---- Peter Dalgaard             Blegdamsvej 3
>   c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
>  (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
>~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list