如何在R中使用readLines删除空白行?

Fnz*_* Xx 5 r

如果文件中有很多空白行,如何在R中使用readLines删除空白行?

我知道我可以用blank.lines.skip=Tin read.table删除它,in readLines呢?

另外,如何删除\n带有readLines 的最后一个?

And*_*ndy 5

如何使用选择运算符从 readLines 返回的字符向量中查找非空行?

# character vector mimicking readLine output, lines 2, 4, and 5 are blank
lines <- c("aaa", "", "ccc", "", "")
# [1] "aaa" ""    "ccc" ""    ""

# select lines which are blank
lines[which(lines=="")]
# [1] "" "" ""

# conversely, lines which are not
lines[which(lines!="")]
# [1] "aaa" "ccc"
Run Code Online (Sandbox Code Playgroud)

readLine在上面使用了假数据,但实际上我没有看到 readLines 返回\n空行或最后一行。


42-*_*42- 3

一个可重现的例子:

  Z <- readLines(textConnection("line1 , stuff, other stuff\nline2 ,junk\nline3, a blank two lines follow\n\n\nline6\n"))
>     Z
[1] "line1 , stuff, other stuff"      "line2 ,junk"                     "line3, a blink two lines follow"
[4] ""                                ""                                "line6"                          
[7] ""                               
>     Z1 <- Z[sapply(Z, nchar) > 0] # the zero length lines get removed.
> Z1
[1] "line1 , stuff, other stuff"      "line2 ,junk"                     "line3, a blank two lines follow"
[4] "line6"          
Run Code Online (Sandbox Code Playgroud)

@Andrie 建议你做这样的事情:

> Z <- scan(textConnection("line1 , stuff, other stuff\nline2 ,junk\nline3, a blink two lines follow\n\n\nline6\n"), 
            what="", sep="\n",blank.lines.skip=TRUE)
Read 4 items
>     Z
[1] "line1 , stuff, other stuff"      "line2 ,junk"                     "line3, a blink two lines follow"
[4] "line6" 
Run Code Online (Sandbox Code Playgroud)