[R] How to refer to the last a few rows?

Ben Bolker bolker at ufl.edu
Thu Nov 5 17:14:22 CET 2009




Peng  Yu wrote:
> 
> On Thu, Nov 5, 2009 at 7:24 AM, jim holtman <jholtman at gmail.com> wrote:
>> will this do:
>>
>>> x
>>     [,1] [,2] [,3] [,4] [,5]
>> [1,]    1    6   11   16   21
>> [2,]    2    7   12   17   22
>> [3,]    3    8   13   18   23
>> [4,]    4    9   14   19   24
>> [5,]    5   10   15   20   25
>>> tail(x[,tail(seq(ncol(x),3))], 2)
>>     [,1] [,2] [,3]
>> [4,]   24   19   14
>> [5,]   25   20   15
>>>
> 
> I would avoid to type the variable name twice. Because this is very
> inconvenient when the variable name is long.
> 
> a_loooooooooooooooooong_expression_or_variable[nrow(a_loooooooooooooooooong_expression_or_variable),]
> 
> BTW, you misunderstood my question. My question was whether is a
> better way to get the last a few columns than 't(tail(t(x),2))'.
> 
> 

Maybe not. I would say a reasonably standard R-ish way would
be

nc <- ncol(x); x[,(nc-5):nc]

Re: really long variable names, perhaps changing your variable naming style
would
be helpful?

If you frequently want the last few columns, then maybe writing

tailcol <- function(x,n=5) {
   nc <- ncol(x); n <- max(0,nc-n); x[,(nc-n):nc]
}
(or something like that; you should decide what you want to happen
when n>nc)

and putting it in your own personal set of utilities would be helpful ...

-- 
View this message in context: http://old.nabble.com/How-to-refer-to-the-last-a-few-rows--tp25438026p26215786.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list