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
This one takes one more line, but is far more readable:
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.Adding a
dplyr
answer for completeness:head
with a negative index is convenient for this...p.s. your
seq()
example may be written slightly less(?) awkwardly using the named argumentsby
andlength.out
(shortened tolen
) like this-seq(nrow(df),by=-1,len=5)
.