繁体   English   中英

如何用R中的readLines删除空行?

[英]How to delete blank lines with readLines in R?

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

我知道我可以在read.table使用blank.lines.skip=T来删除它,在readLines怎么样?

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

如何使用选择运算符从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

一个可重复的例子:

  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" 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM