[R] how to skip last lines while reading the data in R

Henrique Dallazuanna wwwhsd at gmail.com
Mon Jan 28 16:18:21 CET 2008


Ok, I agree, but I assume that her don't know the number of rows of file.

In your example:

rev2 <- function(x,n=100,m=5){

   for(i in 1:n){
     y=x[1:(length(x)-m)]
   }
   return(y)
}

is needed that open other textConnection - if use the example posted by me.

Is there other option?

On 28/01/2008, Barry Rowlingson <b.rowlingson at lancaster.ac.uk> wrote:
> Henrique Dallazuanna wrote:
> > Perhaps:
> >
> > data <- read.table(textConnection(rev(rev(readLines('data.txt'))[-(1:2)])))
> >
>
>   Euurgh! Am I the only one whose sense of aesthetics is enraged by
> this? To get rid of the last two items you reverse the vector, remove
> the first two items, then reverse the vector again?
>
>   One liners are fine for R Golf games, but in the real world, I'd get
> the length of the vector and cut directly off the end. Consider these:
>
> # reverse/trim/reverse:
> rev1 <- function(x,n=100,m=5){
>    for(i in 1:n){
>      y=rev(rev(x)[-(1:m)])
>    }
>    return(y)
> }
>
> # get length, trim
> rev2 <- function(x,n=100,m=5){
>    for(i in 1:n){
>      y=x[1:(length(x)-m)]
>    }
>    return(y)
> }
>
>   > system.time(rev1(1:1000,10000,5))
>   [1] 1.864 0.008 2.044 0.000 0.000
>   > system.time(rev2(1:1000,10000,5))
>   [1] 0.384 0.008 0.421 0.000 0.000
>
>
>   Result: faster, more directly readable code.
>
>


-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list