【问题标题】:Is there a way to limit the number of seps when doing read.table?做read.table时有没有办法限制seps的数量?
【发布时间】:2022-01-04 08:39:03
【问题描述】:

我有一段要预处理的文本数据, 并且这些数据的形式是:

[num|num|<String>]

但是, 中有空格、逗号和"|"。 因此,无法使用"|" 分隔数据。 如何在检索数据时实现对分区数或 readlines 的限制? 我尝试使用flush = TRUE,但它无法使用,因为它会删除 的某些部分。

【问题讨论】:

  • 使用readLines读取数据和正则表达式分隔列?没有看到示例就很难提出解决方案。如果缺少某些文本,则可能意味着存在无法识别的字符。
  • 回复 "seps":你的意思是 "steps"
  • 对于 seps,我在 read.table() 中分开,比如 sep = ","
  • 那么,separators

标签: r


【解决方案1】:

你可能有这样的东西。

123|1234|foo, bar | baz
021|3874|foo, bar | baz
123|1234|foo, bar | baz
123|1234|foo, bar | baz

如果"|" 之前有一个数字(?&lt;=\\d),您可以使用lookbehind。

readLines('tmp.txt') |>
  strsplit('(?<=\\d)\\|', perl=TRUE)
# [[1]]
# [1] "123"            "1234"           "foo, bar | baz"
# 
# [[2]]
# [1] "021"            "3874"           "foo, bar | baz"
# 
# [[3]]
# [1] "123"            "1234"           "foo, bar | baz"
# 
# [[4]]
# [1] "123"            "1234"           "foo, bar | baz"

注意:使用 R >= 4.1。


数据:

write(file='tmp.txt',
'123|1234|foo, bar | baz
021|3874|foo, bar | baz
123|1234|foo, bar | baz
123|1234|foo, bar | baz'
)

【讨论】:

  • 使用strsplit的好技巧,点赞!
  • 天哪。你的预测是正确的。我的数据与您提到的形状相同。这个问题让我很头疼,但你的想法真的很有帮助。非常感谢!
【解决方案2】:

以下类似的想法来自jay.sf's answer(并从那里借用数据):

read.table(
  text = gsub(
    "(?<=\\d)\\|", "\t",
    readLines("tmp.txt"),
    perl = TRUE
  ),
  sep = "\t"
)

给了

   V1   V2             V3
1 123 1234 foo, bar | baz
2  21 3874 foo, bar | baz
3 123 1234 foo, bar | baz
4 123 1234 foo, bar | baz

【讨论】:

  • 整洁的小翻译+1!
猜你喜欢
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 2022-07-20
  • 2016-04-17
  • 2019-04-03
  • 2019-09-28
  • 2017-12-02
  • 1970-01-01
相关资源
最近更新 更多