如果文件中有多个空行,如何在R?
中删除带有readLines的空行我知道我可以blank.lines.skip=T
使用read.table
删除它,readLines
怎么样?
另外,如何删除带有readLines的最后一个\n
?
答案 0 :(得分:3)
如何使用选择运算符从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
。
答案 1 :(得分:3)
可重现的例子:
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"