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

RDataframeRow

R Problem Overview


I have a data frame and I want to remove last N rows from it. If I want to remove 5 rows, I currently use the following command, which in my opinion is rather convoluted:

df<- df[-seq(nrow(df),nrow(df)-4),]

How would you accomplish task, is there a convenient function that I can use in R?

In unix, I would use:

tac file | sed '1,5d' | tac 

R Solutions


Solution 1 - R

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).

Solution 2 - R

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.

Solution 3 - R

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    

Solution 4 - R

Another dplyr answer which is even more readable:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlbyView Question on Stackoverflow
Solution 1 - RSimon O'HanlonView Answer on Stackoverflow
Solution 2 - RAssafView Answer on Stackoverflow
Solution 3 - ROscarView Answer on Stackoverflow
Solution 4 - REdgarView Answer on Stackoverflow