How to import last 100 rows using read.csv() in R

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

Hi I've a huge file and i want to import only the last 100 rows from that file. How can we do that using read.csv() or any alternative?

回答1:

The package R.utils has a function called countLines(). You could do:

l2keep <- 10 nL <- countLines("your.csv") df <- read.csv("your.csv", header=FALSE, skip=nL-l2keep) 


回答2:

If you are on a *nix system, you are better off using the tail -n 100 command to take the last 100 rows. Anything implemented in R would be slower and potentially much slower is your file is truly huge.

If you are using Windows, you may want to take a look at this SO question.



回答3:

You could use the nrows and skip arguments in read.csv. E.g. if you have a file with 10000 rows and you would only like to import the last 100 rows you could try this:

read.csv("yourfile.csv",nrows=100,skip=9900) 

But if it is speed you want, you're probably better off with the solutions given by @Ananda Mahto and @ktdrv



回答4:

The quick and dirty way that works for me - use fread to read large files while setting select = 1 so that only the first column is read. Then use fread again to read data from the desired rows. Fread is much faster than read.csv or other similar variants. More on fread vs read.csv here: Reason behind speed of fread in data.table package in R



回答5:

give appropriate skip parameter in read.csv()



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!