An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20090209/cc46ed76/attachment-0001.pl>
Assigning to a vector while keeping the attributes
3 messages · Alon Wasserman, David Winsemius, Gabor Grothendieck
Not sure what "a" really is. It's not a vector or a list according to the R interpreter. > a <- structure(1:3,x=3) > mode(a) [1] "numeric" > is.vector(a) [1] FALSE > is.list(a) [1] FALSE Experimentation shows that simple indexing provides the functionality you request while append does not. > a[4] <- 10 > a [1] 1 2 3 10 attr(,"x") [1] 3 > a <-append(a, 20) > a [1] 1 2 3 10 20 # appears to have now coerced it to a vector > a [1] 1 2 3 10 20 > is.vector(a) [1] TRUE
David Winsemius On Feb 9, 2009, at 7:09 AM, Alon Wasserman 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.
Try this: a <- structure(1:3, x = 3) b <- "attributes<-"(11:15, attributes(a)) dput(b)
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.