Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop lapply from printing to console

Tags:

r

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
like image 515
Tyler Rinker Avatar asked Oct 20 '12 03:10

Tyler Rinker


3 Answers

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.

like image 149
James Avatar answered Nov 09 '22 03:11

James


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")
like image 22
hadley Avatar answered Nov 09 '22 01:11

hadley


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")
like image 1
andschar Avatar answered Nov 09 '22 02:11

andschar