[R] beginner programming question

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Dec 18 00:23:26 CET 2003


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