Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete blank lines with readLines in R?

Tags:

r

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?

like image 609
Fnzh Xx Avatar asked Aug 08 '12 13:08

Fnzh Xx


2 Answers

How about using selection operators to find the non blank lines from the character vector that is returned by 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"

I used fake readLine data above, however in practice I don't see readLines return \n for blank lines or the last line.

like image 181
Andy Avatar answered Nov 12 '22 09:11

Andy


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" 
like image 39
IRTFM Avatar answered Nov 12 '22 08:11

IRTFM