Nate Thompson Nate Thompson - 3 months ago 8
R Question

R Function - Print When Not Assigned

I see there is another related question, but the answer isnt what I am looking for. I want a function that can be assigned to an object, but still will print the output even when assigned, but not double print it.

In this case:

fun <- function(x) {
print(x+1)
x+1
}
a <- fun(3)


In this case, it would both save to a, and it would print to console, which is what I want.

But in this case:

fun(3)


It would print to the console twice. Is there a way to get the desired result from case 1, without double printing on case 2?

Answer

Assuming that you still want your function to return the 'x+1' value, you could just wrap it in the invisible function:

fun <- function(x) {
  print(x+1)
  invisible(x+1)
}

> fun(3)
[1] 4

> a = fun(3)
[1] 4

> a
[1] 4

This will only print it out once, while still retaining the 'x+1' value.

Comments