【问题标题】:readr::read_lines: Problem with lines length result for empty *txt filesreadr::read_lines:空 *txt 文件的行长度结果问题
【发布时间】:2020-11-03 19:09:45
【问题描述】:

我有 4K *txt 文件,其中行数很重要,因为如果我的 *txt 文件为空,则需要计数为零,如果我有 1 行或更多行,则此信息也很重要。 但是readr 包中的函数read_lines 总是给我1行我有一个空文件,在我的例子中:

library(tidyverse)

# *txt file with 1 line
myfile1<-read_lines("https://raw.githubusercontent.com/Leprechault/trash/main/sample_672.txt")
length(myfile1)
#[1] 1
myfile1
#[1] "0 0.229592 0.382716 0.214286 0.246914"

# *txt file with 0 line
myfile2<-read_lines("https://raw.githubusercontent.com/Leprechault/trash/main/sample_1206.txt")
length(myfile2)
#[1] 1
myfile2
#[1] ""

在 myfile1 中是可以的,因为我有 1 行,但在第二种情况下 (myfile2) 我没有一行并且文件是空的。请问,这个问题怎么解决?

【问题讨论】:

    标签: r readr


    【解决方案1】:

    您可以使用基础 R 中的readLines()。它已经具有正确的行为。

    【讨论】:

      【解决方案2】:

      您可以将read_lines() 放在一个包装函数中,该函数可以执行您想要的操作...

      rl <- function(...) {
          x <- read_lines(...)
          if (identical(x,"")) return(character(0))
          return(x)
      }
      
      rl("https://raw.githubusercontent.com/Leprechault/trash/main/sample_1206.txt")  
      ## character(0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-03
        • 1970-01-01
        相关资源
        最近更新 更多