Home > Enterprise >  print messages at runtime in lapply wrappers
print messages at runtime in lapply wrappers

Time:02-04

I have a function that conditionally prints messages/warnings, e.g. like below:

test <- function(x)
{
  for (i in 1:5)
  {
    if (i == 3)
    {
      warning("test")
      break()
    }
    if (i != 3)
    {
      message(i)
    }
  }
}

The function correctly breaks out of index 3 and prints the warning.

test(1)

1
2
Warning message:
test 

However, when I wrap that function into an lapply, the warning message is only printed at the end:

lapply(1:2, test)

1
2
1
2
[[1]]
NULL

[[2]]
NULL

Warning messages:
1: In FUN(X[[i]], ...) : test
2: In FUN(X[[i]], ...) : test

How can I make sure that the message is printed "per loop"? I.e.

1
2
Warning messages:
1: In FUN(X[[i]], ...) : test
1
2
Warning messages:
1: In FUN(X[[i]], ...) : test

[[1]]
NULL

[[2]]
NULL

CodePudding user response:

You can set immediate warnings globally using options(warn = 1). warning() also has an immediate. argument for specific use:

test <- function(x)
{
  for (i in 1:5)
  {
    if (i == 3)
    {
      warning("test", immediate. = TRUE)
      break()
    }
    if (i != 3)
    {
      message(i)
    }
  }
}

lapply(1:2, test)
1
2
Warning in FUN(X[[i]], ...) : test
1
2
Warning in FUN(X[[i]], ...) : test
[[1]]
NULL

[[2]]
NULL

Note from the documentation:

warning signals a warning condition by (effectively) calling signalCondition. If there are no handlers or if all handlers return, then the value of warn = getOption("warn") is used to determine the appropriate action. If warn is negative warnings are ignored; if it is zero they are stored and printed after the top–level function has completed; if it is one they are printed as they occur and if it is 2 (or larger) warnings are turned into errors. Calling warning(immediate. = TRUE) turns warn <= 0 into warn = 1 for this call only.

  • Related