Remove last N rows in data frame with the arbitrary number of rows

Adding a dplyr answer for completeness:

test_df <- data_frame(a = c(1,2,3,4,5,6,7,8,9,10), 
                      b = c("a","b","c","d","e","f","g","h","i","j"))
slice(test_df, 1:(n()-5))

## A tibble: 5 x 2
#      a b    
#  <dbl> <chr>
#1     1 a    
#2     2 b    
#3     3 c    
#4     4 d    
#5     5 e    

This one takes one more line, but is far more readable:

n<-dim(df)[1]
df<-df[1:(n-5),]

Of course, you can do it in one line by sticking the dim command directly into the re-assignment statement. I assume this is part of a reproducible script, and you can retrace your steps... Otherwise, strongly recommend in such cases to save to a different variable (e.g., df2) and then remove the redundant copy only after you're sure you got what you wanted.


head with a negative index is convenient for this...

df <- data.frame( a = 1:10 )
head(df,-5)
#  a
#1 1
#2 2
#3 3
#4 4
#5 5

p.s. your seq() example may be written slightly less(?) awkwardly using the named arguments by and length.out (shortened to len) like this -seq(nrow(df),by=-1,len=5).


Another dplyr answer which is even more readable:

df %>% filter(row_number() <= n()-5)

Tags:

R

Row

Dataframe