[R] short-hand to avoid use of length() in subsetting vectors?
Nordlund, Dan (DSHS/RDA)
NordlDJ at dshs.wa.gov
Wed Jan 11 00:48:15 CET 2012
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Steve Lianoglou
> Sent: Tuesday, January 10, 2012 3:28 PM
> To: Eric Rupley
> Cc: r-help at r-project.org
> Subject: Re: [R] short-hand to avoid use of length() in subsetting
> vectors?
>
> Hi,
>
> On Tue, Jan 10, 2012 at 6:04 PM, Eric Rupley <erupley at umich.edu> wrote:
> >
> > Hi--
> >
> > I suspect this is a frequently considered (and possibly asked)
> question, but I haven't thus far found an answer:
> >
> > For slicing a vector with x[…], is there a symbol for
> length(x)?
> >
> > I'm seeking a short-hand for referring to the length of vector one is
> trying to index.
> >
> > E.g., for a data.frame, say,
> >
> >> test.frame <-data.frame(matrix(c(1:100),ncol=10,nrow=10,byrow=T))
> >> names(test.frame) <- names(islands)[1:10]
> >
> > is there a short-hand for subsetting
> >
> >> test.frame$Baffin[1:(length(test.frame$Baffin)-3)]
> > [1] 6 16 26 36 46 56 66
> >>
> >>
> >
> > that would allow one to avoid the "(length(some.dataframe$variable)-
> offset)"?
>
> Sadly there is no shorthand of the (exact) type you are looking for.
>
> You can access the data like so, however:
>
> R> head(test.frame$Baffin, -3)
> [1] 6 16 26 36 46 56 66
>
> I think that's as good as you're going to get, but let's see what
> other suggestions pop up.
>
> -steve
>
Steve is probably right. But, here is one suggestion. Since every column of a data frame is the same length, You could try something like
test.frame$Baffin[1:(nrow(test.frame)-3)]
However, it is only a little bit shorter.
Dan
Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204
More information about the R-help
mailing list