R语言 不打开CSV文件就能得到它的行数吗?

kqhtkvqz  于 2023-07-31  发布在  其他
关注(0)|答案(6)|浏览(114)

我有一个大小约为1GB的CSV文件,由于我的笔记本电脑是基本配置,我无法在Excel或R中打开该文件。但出于好奇,我想得到文件中的行数。如果我能做到的话,我该怎么做呢?

ycl3bljg

ycl3bljg1#

对于Linux/Unix:

wc -l filename

字符串
对于Windows:

find /c /v "A String that is extremely unlikely to occur" filename

ruarlubt

ruarlubt2#

选项一:

通过文件连接,count.fields()根据某个sep值(我们在这里不关心)来计算文件每行的字段数。因此,如果我们取结果的长度,理论上我们应该得到文件中的行数(和行数)。

length(count.fields(filename))

字符串
如果有标题行,可以使用skip = 1跳过它

length(count.fields(filename, skip = 1))


还有其他一些参数可以根据您的特定需求进行调整,比如跳过空行。

args(count.fields)
# function (file, sep = "", quote = "\"'", skip = 0, blank.lines.skip = TRUE, 
#     comment.char = "#") 
# NULL


更多信息请参见help(count.fields)
就速度而言还不错。我在一个包含99846行的棒球文件上测试了它。

nrow(data.table::fread("Batting.csv"))
# [1] 99846

system.time({ l <- length(count.fields("Batting.csv", skip = 1)) })
#   user  system elapsed 
#  0.528   0.000   0.503 

l
# [1] 99846
file.info("Batting.csv")$size
# [1] 6153740

**(效率更高)选项2:**另一个想法是使用data.table::fread()只读取第一列,然后获取行数。这会非常快。

system.time(nrow(fread("Batting.csv", select = 1L)))
#   user  system elapsed 
#  0.063   0.000   0.063

nszi6y05

nszi6y053#

根据前1000行的大小估计行数

size1000  <- sum(nchar(readLines(con = "dgrp2.tgeno", n = 1000)))

sizetotal <- file.size("dgrp2.tgeno")
1000 *  sizetotal / size1000

字符串
对于大多数用途来说,这通常已经足够好了,而且对于大型文件来说要快得多。

v9tzhpje

v9tzhpje4#

下面是我用过的东西:

testcon <- file("xyzfile.csv",open="r")
readsizeof <- 20000
nooflines <- 0
( while((linesread <- length(readLines(testcon,readsizeof))) > 0 ) 
nooflines <- nooflines+linesread )
close(testcon)
nooflines

字符串
查看这篇文章了解更多:https://www.r-bloggers.com/easy-way-of-determining-number-of-linesrecords-in-a-given-large-file-using-r/

yzckvree

yzckvree5#

在R中实现Tony的答案:

file <- "/path/to/file"
cmd <- paste("wc -l <", file)
as.numeric(system(cmd, intern = TRUE))

字符串
对于100k行的文件,这比data.table快4倍

>     microbenchmark::microbenchmark(
+         nrow(fread("~/Desktop/cmx_bool.csv", select = 1L)),
+         as.numeric(system("wc -l <~/Desktop/cmx_bool.csv", intern = TRUE))
+     )
Unit: milliseconds
                                                               expr       min        lq
                 nrow(fread("~/Desktop/cmx_bool.csv", select = 1L)) 128.06701 131.12878
 as.numeric(system("wc -l <~/Desktop/cmx_bool.csv", intern = TRUE))  27.70863  28.42997
      mean   median        uq      max neval
 150.43999 135.1366 142.99937 629.4880   100
  34.83877  29.5070  33.32973 270.3104   100

qojgxg4l

qojgxg4l6#

只需在notepad++中打开文件并滚动到文件的末尾。你会找到行数。

相关问题