[R] Assigning to a vector while keeping the attributes

Gabor Grothendieck ggrothendieck at gmail.com
Mon Feb 9 16:30:14 CET 2009

Try this:

a <- structure(1:3, x = 3)
b <- "attributes<-"(11:15, attributes(a))

On Mon, Feb 9, 2009 at 7:09 AM, Alon Wasserman <alon.was at gmail.com> wrote:
> Hi,
> I would like to know how to assign values to a whole vector while keeping
> its attributes. For example, say I have
> a <- structure(1:3,x=3)
> and I want to change the values to 2:4. If I do, a <- 2:4, the attribute x
> will be lost. I have a workaround for this case, which is to use subset
> assignment
> a[1:3] <- 2:4.
> However, what if I want to also change the length of a? Then this workaround
> doesn't work and also assigning into length(a) drops the attributes. More
> severe workarounds (such as keeping the attributes and then reassigning
> them) work, but if there's a simple solution, I'd be happy to use it.
> Thanks,
> Alon
>        [[alternative HTML version deleted]]
> ______________________________________________
> R-help at 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.

More information about the R-help mailing list