Skip to content

Extending a vector to length n

6 messages · Richard Cotton, Gabor Grothendieck, Raubertas, Richard +2 more

#
In general, how can I increase a vector of length m (< n) to length n
by padding it with m - n missing values, without losing attributes?
The two approaches I've tried, using length<- and adding missings with
c, do not work in general:
[1] "2008-01-01" NA
[1] 13879    NA
[1]  1 NA
[1] a    <NA>
Levels: a

Hadley
#
You can save the attributes to a new variable, increase the length, then 
reapply the attributes, e.g.

extend <- function(x, n)
{
   att <- attributes(x)
   length(x) <- n
   attributes(x) <- att
   x
}

a <- as.Date("2008-01-01")
extend(a, 2)
# [1] "2008-01-01" NA

b <- factor("a")
extend(b, 2)
# [1] a    <NA>
# Levels: a

It would, perhaps, be nicer if length had an option to preserve 
attributes.

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}
#
This may not be everything you would like but perhaps its sufficient:
[1] "2008-01-01" NA

Your second example looks ok as is.  Can't tell what you don't
like about it.
On Wed, Apr 15, 2009 at 10:55 AM, hadley wickham <h.wickham at gmail.com> wrote:
1 day later
#
The following approach works for both of your examples:

xx <- rep(x, length.out=n)
xx[m:n] <- NA

Thus:
[1] "2008-01-01" NA
[1] a    <NA>
Levels: a
R. Raubertas
Merck & Co
Notice:  This e-mail message, together with any attachme...{{dropped:12}}
#
Great idea - that's a little faster than my previous approach of
setting length() and then re-adding the attributes.  Thanks!

Hadley

On Thu, Apr 16, 2009 at 12:16 PM, Raubertas, Richard
<richard_raubertas at merck.com> wrote:

  
    
#
Folks:

Not to be picky, but depending on exactly what's meant by "attributes," I
think it's impossible:
NULL
[1] 6 

So "attributes" aren't preserved. The whole point of object orientation and
method dispatch is to deal with this issue in a coherent way.

Cheers,
Bert



-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of hadley wickham
Sent: Thursday, April 16, 2009 10:50 AM
To: Raubertas, Richard
Cc: r-help
Subject: Re: [R] Extending a vector to length n

Great idea - that's a little faster than my previous approach of
setting length() and then re-adding the attributes.  Thanks!

Hadley

On Thu, Apr 16, 2009 at 12:16 PM, Raubertas, Richard
<richard_raubertas at merck.com> wrote: