【问题标题】:Is there a way to select rows from an R script by condition?有没有办法按条件从 R 脚本中选择行?
【发布时间】:2021-08-28 22:52:25
【问题描述】:

该问题与选择数据框或通用 R 对象的行无关,而是如前所述,与选择脚本的行有关。 例如。如何从 R 脚本中选择所有奇数行?

【问题讨论】:

  • 这取决于使用的 IDE/文本编辑器,而不是 R。
  • 您可以将脚本作为文本读取到 data.frame 或字符向量中,然后每隔一行/元素选择一次。但那是......好吧......不知道为什么有人应该这样做或需要这个。

标签: r selection


【解决方案1】:

R

txt <- readLines("path/to/script.R")
writeLines(txt[seq_along(txt) %% 2 == 0], "path/to/script_evenlines.R")
writeLines(txt[seq_along(txt) %% 2 == 1], "path/to/script_oddlines.R")

sed

(在 bash 或类似的 shell 提示符下。)

sed -ne '0-2p' path/to/script.R > path/to/script_evenlines.R
sed -ne '1~2p' path/to/script.R > path/to/script_oddlines.R

这可以扩展到保存每个Nth 行

sed -ne '0-Np' path/to/script.R

删除每个Nth 行

sed -e '0-Nd' path/to/script.R

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2021-10-21
    • 2011-07-25
    • 2019-12-31
    • 2013-07-12
    • 2019-08-07
    • 2021-02-25
    相关资源
    最近更新 更多