51

When I use lapply and print to the console it prints unwanted [[i]]NULL though I want the intended message to print to the console. I've tried suppressWarnings and suppressMessages but these do not remove the unwanted offender. I searched lapply and don't see an argument to silence it. This is more aesthetic as it doesn't interfere with the function. I'm not opposed to allternative printing to the console so long as the user can turn it off if they wish.

Here's an example function, the output and what I'd like to get:

Sample function:

FUN <- function(x) {
    FUN2 <- function(z) message(z)
    lapply(1:3, function(i) FUN2(paste(x, i)))
}

FUN("hello")

Output:

hello 1
hello 2
hello 3
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

Desired Output:

hello 1
hello 2
hello 3
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519

3 Answers3

64

Use invisible, eg:

invisible(FUN("hello"))
hello 1
hello 2
hello 3

You can wrap it around the lapply call in the function too to make it tidier.

James
  • 65,548
  • 14
  • 155
  • 193
  • Perfect. I'll add mark it as correct as soon as the time expires. Works great (I wrapped the call to `lapply` as you suggested), – Tyler Rinker Oct 20 '12 at 03:38
  • Still not sure why this works. I've used invisible many times but not for this purpose. – Tyler Rinker Oct 20 '12 at 03:44
  • 2
    It temporarily disables printing of the returned object. – James Oct 20 '12 at 07:23
  • 4
    It's not `lapply` printing its progress as you seem to think, its R printing the returned object as James says. That's why there's no option to `lapply` that you could see. Doing `junk <- FUN("hello")` would have the same visual effect. – Spacedman Oct 20 '12 at 08:37
9

Use l_ply from plyr:

library(plyr)
FUN <- function(x) {
    FUN2 <- function(z) message(z)
    l_ply(1:3, function(i) FUN2(paste(x, i)))
}
FUN("hello")
hadley
  • 102,019
  • 32
  • 183
  • 245
1

You could use a plain ol' for loop instead of lapply():

FUN <- function(x) {
  for (i in 1:3) {
    message(paste0(x, i))
  }
}
FUN("hello")
andschar
  • 3,504
  • 2
  • 27
  • 35