删除数据帧中任意行数的最后N行 [英] Remove last N rows in data frame with the arbitrary number of rows

查看:128
本文介绍了删除数据帧中任意行数的最后N行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想删除最后N行。
如果我要删除5行,我目前使用以下命令,这在我看来是相当复杂的:

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

你将如何完成任务,是否有一个方便的功能,我可以在R中使用?



在unix中,我会使用:

  tac文件| sed'1,5d'| tac 


解决方案

head 负数索引对于这个方便...

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

使用 seq() c> length.out (缩写为 len )像这样 -seq(nrow(df))by = -1 ,len = 5)


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 

解决方案

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

这篇关于删除数据帧中任意行数的最后N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆