readr::read_lines:空 *txt 文件的行长度结果有问题
readr::read_lines: Problem with lines length result for empty *txt files
我有 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) 我没有一行,文件是空的。请问,我该如何解决这个问题?
您可以将 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)
您可以使用基础 R 中的 readLines()
。它已经具有正确的行为。
我有 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) 我没有一行,文件是空的。请问,我该如何解决这个问题?
您可以将 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)
您可以使用基础 R 中的 readLines()
。它已经具有正确的行为。