Search code examples
rsapply

How can a function which prints be called repeatedly without returning the value of what was printed and without a for loop?


I recently wrote for(i in 1:100){foo(i,bar)} as the last line in a script. In this case, the last line of foo is a call to print and I definitely do not want to see the return values of foo. I only want the printing. This for loop works, but it feels unidiomatic to use a loop like this in R. Is there any more idiomatic way to achieve this? foo must take each i in 1:100 individually before being called, so foo(1:100,bar) won't work.

sapply(1:100,function(x) foo(x,bar)) seems more idiomatic, but it gives me both the return values of foo and its printing. I had considered using do.call, but having to use as.list(1:100) disgusted me. What are my alternatives?

Minimum example:

foo<-function(i,bar)
{
  print(paste0("alice",i,bar,collapse = ""))
}
for(i in 1:100){foo(i,"should've used cat")}
sapply(1:100,function(x) foo(x,"ugly output"))```

Solution

  • You can use invisible in base R to suppress function return output:

    invisible(sapply(1:5, function(x) foo(x, "ugly")))
    
    [1] "alice1ugly"
    [1] "alice2ugly"
    [1] "alice3ugly"
    [1] "alice4ugly"
    [1] "alice5ugly"
    

    You can also use purrr::walk - it is like sapply in that it executes a function over iterated values, but wrapped with invisible by default:

    purrr::walk(1:100, ~foo(., "ugly"))