[R] Extending a vector to length n
Richard.Cotton at hsl.gov.uk
Richard.Cotton at hsl.gov.uk
Wed Apr 15 17:30:47 CEST 2009
> 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:
>
> > a <- as.Date("2008-01-01")
> > c(a, NA)
> [1] "2008-01-01" NA
> > length(a) <- 2
> > a
> [1] 13879 NA
>
>
> > b <- factor("a")
> > c(b, NA)
> [1] 1 NA
> > length(b) <- 2
> > b
> [1] a <NA>
> Levels: a
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}}
More information about the R-help
mailing list