5

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

我知道我可以用blank.lines.skip=Tinread.table删除它, in 怎么样readLines

另外,如何\n使用 readLines 删除最后一个?

4

2 回答 2

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"

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

于 2012-08-08T13:53:25.307 回答
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"          

@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" 
于 2012-08-08T15:06:34.063 回答