0

I want to save the number that is printed using the print() function R. For example, I have a print(bf(X, Y) command that prints a sentence "Estimated value is : 0.5". How to save only the number 0.5 to a txt/excel file? because I have a loop that will print hundreds of that sentence with different numbers and I want to be able to save all the numbers in a file automatically. Thanks!

Rlearner
  • 53
  • 3
  • Please make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Martin Gal Aug 09 '21 at 22:11
  • How do you want these numbers to be saved? Just a long list of numbers? Any additional information? – Martin Gal Aug 09 '21 at 22:15
  • Does this answer your question? [how to save print(i/j) to an output file?](https://stackoverflow.com/questions/5119564/how-to-save-printi-j-to-an-output-file) – Yirmi Aug 09 '21 at 22:15
  • @MartinGal Yes, I want to save those numbers to be in a long vector. For example, I will create a null vector of length 100. And for each of the 100 loops, I will save only the number to the vector and at the end the vector will be full with the numbers. But to do that, I will need to figure out how to extract only the number 0.5 from the printed sentence. – Rlearner Aug 09 '21 at 22:18
  • 3
    A little more context would be helpful. If at all possible, it's cleaner to go "upstream" and extract the number from wherever `bf(X, Y)` is getting it from, rather than operating on the string returned by `bf()` to extract the number. What is the `bf()` function? Is it something you can modify, or create a modified version of, to return a number rather than a string? – Ben Bolker Aug 09 '21 at 22:27

2 Answers2

1

Suppose, your function bf(X,Y) returns a string like `"Estimated value is : 0.5". You could use

library(stringr)

as.double(str_extract(bf(X, Y), "\\d+.\\d+"))

to extract the number from this string. Assign it to a vector/data.frame and write it into a .csv.

With base R you could use

as.double(unlist(regmatches(bf(X, Y), gregexpr("\\d+.\\d+", bf(X, Y)))))
Martin Gal
  • 16,640
  • 5
  • 21
  • 39
1

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))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213