【问题标题】:Final element with '.' does not write correctly to file带有“.”的最后一个元素没有正确写入文件
【发布时间】:2021-06-07 04:31:32
【问题描述】:

我有一个很长的十进制值向量:

spect <- c(0.0005862, 0.0005983, 0.0006225, 0.0006637, 0.0006622, 0.0006197, 0.0005990, 0.0005983, 0.0006247, 0.0006707, 0.0006641)

使用 gsub,我尝试每次取 5 个元素并写入文件中的一行(感谢用户 akrun)

cat(gsub("\\s*(([0-9.]+\\s+){1,4}\\d+)", "\\1\n",
         paste(unlist(spect), collapse="      ")), '\n', file = "file.txt")

但输出看起来像这样:

0.0005862      0.0005983      0.0006225      0.0006637      0
.0006622      0.0006197      0.000599      0.0005983      0
.0006247      0.0006707      0
.0006641 

是什么导致最后一个元素没有正确写入并在'.'之前开始一个新行?

结果应该是这样的:

0.0005862      0.0005983      0.0006225      0.0006637      0.0006622 
0.0006197      0.000599      0.0005983      0.0006247      0.0006707 
0.0006641 

【问题讨论】:

  • 处理这个问题的方式多么奇怪。我会做length(spect) &lt;- (length(spect) %/% 5 + 1) * 5; spect[is.na(spect)] &lt;- ""; DF &lt;- data.frame(matrix(spect, ncol = 5, byrow = TRUE)),然后使用write.table 进行适当的设置。如果您不想修改输入向量,请在函数中进行包装。
  • 正则表达式在字符级别描述文本。它们完全不适合基于某些非文本含义来操作非文本数据。我通常会在这里使用splitcut 的组合,但在这种特殊情况下,它比 Ronak 的优雅答案要复杂得多。
  • 感谢您的解释,我刚刚开始更多地使用 R

标签: r regex file-io gsub


【解决方案1】:

如果您有矢量输入,则不需要正则表达式来执行此操作。试试看:

cat(paste0(tapply(spect, ceiling(seq_along(spect)/5), 
    paste0, collapse = '     '), collapse = '\n'), file = "file.txt")

【讨论】:

  • 非常细微的变化:writeLines(paste(tapply(spect, (seq_along(spect) - 1L) %/% 5L, paste, collapse = '\t'), collapse = '\n'))(使用更自然的索引编号,避免了ceiling)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
相关资源
最近更新 更多