Suppress automatic output to console in R - r

The function callmultmoments computes moments of the normal distribution.
The function automatically prints "Sum of powers is odd. Moment is 0." if the sume of the powers is odd. Is there any way to supress that under the condition that the original function should stay untouched.
Ex:
require(symmoments)
# Compute the moment for the 4-dimensional moment c(1,1,3,4):
m.1134 <- callmultmoments(c(1,1,3,4))
EDIT:
As described here we can use
## Windows
sink("nul")
...
sink()
## UNIX
sink("/dev/null") # now suppresses
.... # do stuff
sink() # to undo prior suppression, back to normal now
However, I am writing a package so I want it to be platform independent. Any ideas what to do instead?

The issue is due to the fact that the function has multiple print statements, where stop, warning, or message would have been appropriate so that people can use suppressWarnings or suppressMessages.
You can work arount it using invisible(capture.output()) around your whole assignment (not just the right side).
f1 <- function(n, ...){
print("Random print statement")
cat("Random cat statement\n")
rnorm(n = n, ...)
}
f1(2)
#> [1] "Random print statement"
#> Random cat statement
#> [1] -0.1115004 -1.0830523
invisible(capture.output(x <- f1(2)))
x
#> [1] 0.0464493 -0.1453540
See also suppress messages displayed by "print" instead of "message" or "warning" in R.

This message from callmultmoments can be suppressed by simply avoiding a moment that is not even. Any odd central moment, such as c(1,1,3,4) as in your example will have an expected value of 0 mathematically. That is, the expected value of a CENTRAL moment such as E[X^1 Y^1 Z^3 W^4], where the sum of powers, such as 1+1+3+4, is odd is automatically 0.

Related

R - how to locate fail in parallel loop (pblapply)

I'm working in R, and using the function pblapply() to make parallel processing. I love this function because it shows a progress bar (very useful for estimate very long execution).
Let's say I have a huge dataset, that I split in 500 smaller subdatasets. I will share them through different threads for parallel processing. But if one subdataset generate an error, the whole pblapply() loop failed, and I don't know which of the 500 small subdatasets generated the error. I have to check them one by one. When I do such loop with the R base for() function, I can add print(i) that will help me locate the error.
Q) Can I do something similar with pblapply(), display a value to tell me which subdataset is currently executing (even if several are displayed at the same time, as several subdatasets are manipulated at the same time by the different threads). It will save my time.
# The example below generate an error, we can guess where because it's very simple.
# With the **pblapply()**, I can't know which part generate the error,
# whereas with the loop, testing one by one, I can find it, but it could be very long with more complex operation.
library(parallel)
library(pbapply)
dataset <- list(1,1,1,'1',1,1,1,1,1,1)
myfunction <- function(x){
print(x)
5 / dataset[[x]]
}
cl <- makeCluster(2)
clusterExport(cl = cl, varlist = c('dataset', 'myfunction'), envir = environment())
result <- pblapply(
cl = cl,
X = 1:length(dataset),
FUN = function(i){ myfunction(i) }
)
stopCluster()
# Error in checkForRemotErrors(vaL) :
# one node produced errors: non-numeric argument to binary operator
for(i in 1:length(dataset)){ myfunction(i) }
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# Error in 5/dataset[[x]] : non-numeric argument to binary operator
One simple way would be to use tryCatch on the part that can cause an error, e.g.:
myfunction <- function(x){
print(x)
tryCatch( 5 / dataset[[x]] , error=function(e) NULL)
}
This way, you get NULL (or whatever you choose) for cases with an error, and can deal with that later in your code.
which(lengths(result)==0)
would tell you which list elements had an error.
You could then examine what happened exactly and implement code that properly identifies and deals with (or prevents) problematic input.

Complex numbers in R vs. Matlab

I observed the following phenomenon when using R and Matlab.
When I apply log to a negative number in R, I get the following error message:
Warning message:
In log(-1) : NaNs produced
However, when I apply log to a negative number in Matlab, I get e.g., the following complex numbers:
log(-1): 0.0000 + 3.1416i
log(-5): 1.6094 + 3.1416i
Is there any way to achieve the same behavior in R? Or is there anything in favor of the default option in R?
log gives you complex when you give it complex in the first place.
log(-1+0i)
# [1] 0+3.141593i
log(-5+0i)
# [1] 1.609438+3.141593i
I don't know why it doesn't give an option to do this by default, but then again I don't work in complex numbers all the time.
If you want to do this programmatically, you can use as.complex:
log(as.complex(-1))
# [1] 0+3.141593i
or even make a helper function simplify it for you:
mylog <- function(x, ...) log(as.complex(x), ...)
mylog(-1)
# [1] 0+3.141593i

How to use `call()` with arguments that update?

x <- 1
test_call <- call(">", x, 0)
eval(test_call)
[1] TRUE
x <- -1
eval(test_call)
[1] TRUE
I have a list of call objects that I want to evaluate from time to time. However, as shown in this example, when test_call is being called the 2nd time, the value of x is not updated within test_call - The 2nd output is expected to be FALSE.
I know I can get around by using parse() instead of call() but parse() really makes the code hard to read... Any workaround if I want to stick with call?

How to keep running the code in main file after calling the function to get input value from user in R programming

I have 2 files:
1. sub file: get_input_template.R : this file contains the function to get input from user.
####################################
fun <- function(){
x <- readline("What is the value of x?")
x <- as.numeric(unlist(strsplit(x, ",")))
return(x)
}
####################################
main.R: this file is main function and it will:
step 1: call the 1st file to ask user input value and assign that value to variable n.
step 2: continue doing something in my main program. Let's take simple task, for e.g, print out the value of n.
Here is my program:
####################################
source("get_input_template.R")
n<-fun()
sprintf("input value n = %s",n)
####################################
The problem is that when I run my main program fully, it shows an error since it doesn't stop at the 2nd line n<-fun() for user to input value. Therefore, i got an error:
---------------------------
Warning message:
In fun() : NAs introduced by coercion
---------------------------
How can I say R to stop running at 2nd line, and allow user to input data, and then print that input into the console. I know that I can fix it by moving sprintf("input value n = %s",n) into the subfile,but, it's not the way I want. How can i do it if I want to keep that line of code in the main file only?
Thanks in advance.
This is caused by the way R parse and interpret your code, to make it simpler what happens is the same that
> source("get_input_template.R") # you run this
> n<-fun() # then this
What is the value of x? # this appears and instead of giving the value you run
sprintf("input value n = %s",n) # you run this final line
if add print(x) just after readline you can see this
> source("UI/read console.R")
> n<-fun()
What is the value of x? sprintf("input value n = %s",n) # at this point R pauses and it is provided with "sprintf("input value n = %s",n)" as value of x
[1] "sprintf(\"input value n = %s\",n)"
Warning message:
In fun() : NAs introduced by coercion
You can solve this by wrapping your code in a function
f <- function(){
source("UI/read console.R")
n<-fun()
sprintf("input value n = %s",n)
}
and then just running:
f()
The reason why it make different is that running a bunch of lines R executes them one by one, as soon as one statement finishes the following is run (and in your issue the third line is provided as input to the second :) ). In a function this doesn't happen, all the code in it is like part of one single statement (the function itself) so, when R is asking you to type something, the following line won't be executed.

Why are arguments to replacement functions not evaluated lazily?

Consider the following simple function:
f <- function(x, value){print(x);print(substitute(value))}
Argument x will eventually be evaluated by print, but value never will. So we can get results like this:
> f(a, a)
Error in print(x) : object 'a' not found
> f(3, a)
[1] 3
a
> f(1+1, 1+1)
[1] 2
1 + 1
> f(1+1, 1+"one")
[1] 2
1 + "one"
Everything as expected.
Now consider the same function body in a replacement function:
'g<-' <- function(x, value){print(x);print(substitute(value))}
(the single quotes should be fancy quotes)
Let's try it:
> x <- 3
> g(x) <- 4
[1] 3
[1] 4
Nothing unusual so far...
> g(x) <- a
Error: object 'a' not found
This is unexpected. Name a should be printed as a language object.
> g(x) <- 1+1
[1] 4
1 + 1
This is ok, as x's former value is 4. Notice the expression passed unevaluated.
The final test:
> g(x) <- 1+"one"
Error in 1 + "one" : non-numeric argument to binary operator
Wait a minute... Why did it try to evaluate this expression?
Well the question is: bug or feature? What is going on here? I hope some guru users will shed some light about promises and lazy evaluation on R. Or we may just conclude it's a bug.
We can reduce the problem to a slightly simpler example:
g <- function(x, value)
'g<-' <- function(x, value) x
x <- 3
# Works
g(x, a)
`g<-`(x, a)
# Fails
g(x) <- a
This suggests that R is doing something special when evaluating a replacement function: I suspect it evaluates all arguments. I'm not sure why, but the comments in the C code (https://github.com/wch/r-source/blob/trunk/src/main/eval.c#L1656 and https://github.com/wch/r-source/blob/trunk/src/main/eval.c#L1181) suggest it may be to make sure other intermediate variables are not accidentally modified.
Luke Tierney has a long comment about the drawbacks of the current approach, and illustrates some of the more complicated ways replacement functions can be used:
There are two issues with the approach here:
A complex assignment within a complex assignment, like
f(x, y[] <- 1) <- 3, can cause the value temporary
variable for the outer assignment to be overwritten and
then removed by the inner one. This could be addressed by
using multiple temporaries or using a promise for this
variable as is done for the RHS. Printing of the
replacement function call in error messages might then need
to be adjusted.
With assignments of the form f(g(x, z), y) <- w the value
of z will be computed twice, once for a call to g(x, z)
and once for the call to the replacement function g<-. It
might be possible to address this by using promises.
Using more temporaries would not work as it would mess up
replacement functions that use substitute and/or
nonstandard evaluation (and there are packages that do
that -- igraph is one).
I think the key may be found in this comment beginning at line 1682 of "eval.c" (and immediately followed by the evaluation of the assignment operation's RHS):
/* It's important that the rhs get evaluated first because
assignment is right associative i.e. a <- b <- c is parsed as
a <- (b <- c). */
PROTECT(saverhs = rhs = eval(CADR(args), rho));
We expect that if we do g(x) <- a <- b <- 4 + 5, both a and b will be assigned the value 9; this is in fact what happens.
Apparently, the way that R ensures this consistent behavior is to always evaluate the RHS of an assignment first, before carrying out the rest of the assignment. If that evaluation fails (as when you try something like g(x) <- 1 + "a"), an error is thrown and no assignment takes place.
I'm going to go out on a limb here, so please, folks with more knowledge feel free to comment/edit.
Note that when you run
'g<-' <- function(x, value){print(x);print(substitute(value))}
x <- 1
g(x) <- 5
a side effect is that 5 is assigned to x. Hence, both must be evaluated. But if you then run
'g<-'(x,10)
both the values of x and 10 are printed, but the value of x remains the same.
Speculation:
So the parser is distinguishing between whether you call g<- in the course of making an actual assignment, and when you simply call g<- directly.

Resources