【问题标题】:Print first few lines of a text file in R在 R 中打印文本文件的前几行
【发布时间】:2023-03-17 00:29:01
【问题描述】:

我有一个没有明显表格或其他结构的文本文件,例如内容

some text on line 1
some more text on line 2
even more text on the third line
etc

将文件中的前几行(比如 2 行)文本打印到控制台的最优雅和类似 R 的方式是什么?

选项 1readLines

readLines('file.txt', n=2)
# [1] "some text on line 1"      "some more text on line 2"

n=2 选项很有用,但我想要原始文件内容,而不是单独的行作为向量的元素。

选项 2file.show

file.show('file.txt')
# some text on line 1
# some more text on line 2
# even more text on the third line
# etc

这种输出格式是我希望看到的,但是缺少限制行数的选项,例如 readLines 中的 n=2

选项 3system('head')

system('head -n2 file.txt')
# some text on line 1
# some more text on line 2

这正是我想要得到的输出,但我不确定这是否适用于所有平台,并且为这样一个简单的任务调用外部命令有点尴尬。

可以将readLines 解决方案与paste 和 cat 结合使用来格式化输出,但这似乎太过分了。像file.head 这样的简单命令会很好,或者file.show 中的n=2 参数会很好,但都不存在。在 R 中实现这一目标的最优雅、最紧凑的方法是什么?

为了澄清这里的目标:这是写一个 R 教程,其中的叙述类似于“......我们现在已经将我们的数据写入一个新的文本文件,所以让我们看看它是否有效在前几行......”。此时,使用基本 (update: 或 tidyverse) 函数的简单而紧凑的 R 表达式将非常有用。

【问题讨论】:

  • head('file.txt') 只返回'file.txt'
  • 我能想到的最接近的是你已经描述过的,但它不需要使用pastecat(readLines("file.txt", n = 2), sep = "\n").
  • 你说得对,我不知道为什么我认为需要pastecat。我稍微修改了问题。
  • 为什么@Benjamin 的建议不合适?似乎正是你想要的。

标签: r tidyverse


【解决方案1】:

writeLinesreadLines 一起使用:

writeLines(readLines("file.txt", 2))

给予:

some text on line 1
some more text on line 2

这也可以写成以下管道。它给出了相同的输出:

library(magrittr)

"file.txt" %>% readLines(2) %>% writeLines

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    相关资源
    最近更新 更多