如何用R中的readLines删除空行?(How to delete blank lines with readLines in R?)

编程入门 行业动态 更新时间:2024-10-23 21:29:35
如何用R中的readLines删除空行?(How to delete blank lines with readLines in R?)

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

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

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

If there are many blank lines in a file, how to delete blank lines with readLines in R?

I know I can use blank.lines.skip=Tin read.table to delete it, how about in readLines?

Also, how do I delete the last \n with readLines?

最满意答案

一个可重现的例子:

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"

A reproducible example:

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 was suggesting you do something like this:

> 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"

更多推荐

本文发布于:2023-08-01 04:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1352825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空行   如何用   readLines   lines   delete

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!