首页 > 解决方案 > 如何在 R 中保存打印字符串中的数字

问题描述

我想保存使用 print() 函数 R 打印的数字。例如,我有一个 print(bf(X, Y) 命令打印句子“估计值为:0.5”。如何只保存数字0.5 到 txt/excel 文件?因为我有一个循环,可以打印数百个不同数字的句子,我希望能够自动将所有数字保存在文件中。谢谢!

标签: r

解决方案


I agree with @Ben Bolker. Instead of operating on string you should return the number from the function bf. You can take the print statement outside the function.

For example, if the current state of the function is like this -

bf <- function(X, Y) {
  #...some code
  #...some code
  #res <- calculation for res
  print(c("Estimated value is : ", res))
}

Change it to -

bf <- function(X, Y) {
  #...some code
  #...some code
  #res <- calculation for res
  res
}

So you can save the output of the function in a variable (res <- bf(X, Y)). If you need the print statement you can add it outside the function.

res <- bf(X, Y)
print(c("Estimated value is : ", res))

推荐阅读