【问题标题】:How to delete blank lines with readLines in R?如何在 R 中使用 readLines 删除空白行?
【发布时间】:2012-08-08 13:36:59
【问题描述】:

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

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

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

【问题讨论】:

  • 也许您应该改用scan,它比readLines 提供更好的控制。

标签: r


【解决方案1】:

如何使用选择运算符从 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 用于空行或最后一行。

【讨论】:

    【解决方案2】:

    一个可重现的例子:

      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" 
    

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多