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=T
in read.table
to delete it, how about in readLines
?
Also, how do I delete the last \n
with readLines?
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With