On 10/05/2013 10:50 AM, Rui Barradas wrote:
Hello,
There's at least one example where only the form attr(x, "foo") <- "bar"
would work, not the other form. If you want to set attributes
programatically, use the first form, like in the function below. Note
that the example is artificial.
setAttr <- function(x, attrib, value){
attr(x, attrib) <- value
x
}
x <- 1:4
setAttr(x, "foo", "bar")
You cannot make
attribute(x)$attrib <- value
But
attributes(x)[[attrib]] <- value
would be fine. I don't know why Murat thought there would be different
consistency checks; I'd assume the main difference would be that attr()
would be quicker. (It does a lot less: attributes(x)[[attrib]] <- value
essentially does
temp <- attributes(x)
temp[[attrib]] <- value
attributes(x) <- temp
and there are a lot of wasted operations there.)
Duncan Murdoch
Hope this helps,
Rui Barradas
Em 09-05-2013 18:35, Murat Tasan escreveu:
> hi all -- i looked through the R Language Definition document, but couldn't
> find any particular warning or example that would clarify the best use of
> attribute setting for R objects.
>
> let x be some R object, and i'd like to add attribute "foo" with value
> "bar".
>
> case 1:
>> attr(x, "foo") <- "bar"
>
> case 2:
>> attributes(x)$foo <- "bar"
>
> in both cases, attributes(x) reveals the appropriate setting has taken
> place.
> i'm assuming that attr(...) is 'safer' in the sense that perhaps
> consistency checks are made?
> (almost like a generic accessor/setter method?)
> but i also haven't seen any examples where case 2 (above) would bad... is
> there are trivial such example out there?
>
> BTW -- the cause for interest here is when dealing with dendrogram objects,
> for which much of the useful data are stored as attributes, and where
> running dendrapply means having to explicitly set attribute values to
> retain the tree structure in the resulting object.
>
> cheers,
>
> -m
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.