如何用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"更多推荐
发布评论