I went through the R documentation and I could not find a clue for this. So the problem is that it seems that l$sigm2 is also assigned when l$sigm2_prior is assigned. Does R behave like this because their similar names? Is there a way go around it?
Function call:
l$sigm2 is not assigned if I change l$sigm2_prior 's name to l$prior.
lik_gaussian(lik=lik[[1]],sigm2_prior=pn[[1]], debug=TRUE);
function:
lik_gaussian <-function(...){
l <- list(...);
inputarray <- NULL;
if(!(length(l$lik)==0)){
inputarray <- c(l$lik);
}
if(!(length(l$sigm2)==0)){
inputarray <- c(inputarray, l$sigm2);
}
if(!(length(l$sigm2_prior)==0)){
inputarray <- c(inputarray,l$sigm2_prior);
}
print(inputarray);
return(inputarray)
}
Thanks in advance.
The '$' operator uses partial matching. That is, if you evaluate l$sigm2 it will actually match to l$sigm2_prior as well. To use exact matching you need to use '[[' or and the name of the object as a string:
l[['sigm2_prior']]
'[[' differs from '$' in that it has the exact argument set to TRUE by default. Se also:
?'$'
Related
I need help on returning a value/object from function
noReturnKeyword <- function(){
'noReturnKeyword'
}
justReturnValue <- function(){
returnValue('returnValue')
}
justReturn <- function(){
return('justReturn')
}
When I invoked these functions: noReturnKeyword(), justReturnValue(), justReturn(), I got output as [1] "noReturnKeyword", [1] "returnValue", [1] "justReturn" respectively.
My question is, even though I have not used returnValue or return keywords explicitly in noReturnKeyword() I got the output (I mean the value returned by the function).
So what is the difference in these function noReturnKeyword(), justReturnValue(), justReturn()
What is the difference in these words returnValue('') , return('')? are these one and the same?
When to go for returnValue('') and return('') in R functions ?
In R, according to ?return
If the end of a function is reached without calling return, the value of the last evaluated expression is returned.
return is the explicite way to exit a function and set the value that shall be returned. The advantage is that you can use it anywhere in your function.
If there is no explicit return statement R will return the value of the last evaluated expression
returnValueis only defined in a debugging context. The manual states:
the experimental returnValue() function may be called to obtain the
value about to be returned by the function. Calling this function in
other circumstances will give undefined results.
In other words, you shouldn't use that except in the context of on.exit. It does not even work when you try this.
justReturnValue <- function(){
returnValue('returnValue')
2
}
This function will return 2, not "returnValue". What happened in your example is nothing more than the second approach. R evaluates the last statement which is returnValue() and returns exactly that.
If you use solution 1 or 2 is up to you. I personally prefer the explicit way because I believe it makes the code clearer. But that is more a matter of opinion.
I have a package which provides a script and some functions. Within the script I assign a variable which will be used by the function. This works if the function gets executed within the script but might fail if I just call the function since the variable doesn't exist.
If I use devtools::check() I get warnings, that the variable within the function isn't defined. How can I handle this properly?
Edit
I am thinking about to use get() within the function to assign the variable within the function to get rid of this warnings. So the question is, is myp2 the correct way of doing something like this? Maybe some trycatch to handle errors?
ab <- c(1,2,3)
myp1 <- function() {
print(ab)
return(1)
}
myp2 <- function() {
ab <- get('ab')
print(ab)
return(1)
}
myp1()
myp2()
You could do something like
if(!exists("your variable")){
stop("You have not defined your variable")}
This would check to see if what you are looking for exists. A better practice would be to define the variable in the function and have the default value be the name of the thing for which you are looking.
myp <- function(x) {
print(x)
return(1)
}
ab <- c(1,2,3)
myp(x = ab)
If possible, it would be also better to substitute the script with a function.
I am not entirely sure I understand what substitute does, although I've used in it code before. Today I encountered in shiny::exprToFunction the following lines of code:
function (expr, env = parent.frame(2), quoted = FALSE, caller_offset = 1)
{
expr_sub <- eval(substitute(substitute(expr)),
...
}
Can someone please explain why nested substitute is used here? A easy to run example would really help.
Take a look at
a<-function(aa) {
b(aa)
}
b<-function(bb) {
z(bb)
}
z<-function(zz) {
print(substitute(zz))
print(substitute(substitute(zz)))
print(eval(substitute(substitute(zz)), parent.frame()))
}
q<-5
a(q)
# bb
# substitute(bb)
# aa
The first/inner substitute grabs the name/symbol that was passed to the called function. The second/outer substitute() simply wraps a substitute() command around that discovered name/symbol. Then that substitute() is evaluated in the parent environment where it came from.
The method of using substitute to capture variable names only works when parameters are still promises; that is, they have not yet been evaluated.
I would like to pass a key/value pair from my R code to a java function.
My java function has argument Map<String,String > .
How can I write R function which calls my Java function and pass values to map ??
EDIT :
config <- list(Portname="PORT.H.2",MktValue="8000000",WtScheme="Closed")
createPortfolio<-function(config)
{
m <- .jnew("java/util/HashMap")
for( key in names(config)){
m$put( key, config[key])
}
m
getting
Error in FUN(X[[2L]], ...) :
Sorry, parameter type `NA' is ambiguous or not supported.
How about trying something like this?
m <- .jnew("java/util/HashMap")
m$put( "key", "value" )
I think you meant
for (key in names(config)) m$put(key, config[[key]])
since you want to pass string as value to put and not a list.
(Consider asking on the rJava mailing list stats-rosuda-devel to get a more prompt answer)
For people, like myself, who had this issue and don't have access to the Java code, it seems to be possible to make a HashMap, and cast it to a Map, like this:
m <- .jnew("java/util/HashMap")
m$put( "key", "value" )
map <- .jcast(m, "java/util/Map")
my R code ends up containing plethora of statements of the form:
if (!is.null(aVariable)) {
do whatever
}
But this kind of statement is hard to read because it contains two negations. I would prefer something like:
if (is.defined(aVariable)) {
do whatever
}
Does a is.defined type function that does the opposite of !is.null exist standard in R?
cheers,
yannick
You may be better off working out what value type your function or code accepts, and asking for that:
if (is.integer(aVariable))
{
do whatever
}
This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.
Alternatively, just make the function you want:
is.defined = function(x)!is.null(x)
If it's just a matter of easy reading, you could always define your own function :
is.not.null <- function(x) !is.null(x)
So you can use it all along your program.
is.not.null(3)
is.not.null(NULL)
Ian put this in the comment, but I think it's a good answer:
if (exists("aVariable"))
{
do whatever
}
note that the variable name is quoted.
I have also seen:
if(length(obj)) {
# do this if object has length
# NULL has no length
}
I don't think it's great though. Because some vectors can be of length 0. character(0), logical(0), integer(0) and that might be treated as a NULL instead of an error.
To handle undefined variables as well as nulls, you can use substitute with deparse:
nullSafe <- function(x) {
if (!exists(deparse(substitute(x))) || is.null(x)) {
return(NA)
} else {
return(x)
}
}
nullSafe(my.nonexistent.var)
The shiny package provides the convenient functions validate() and need() for checking that variables are both available and valid. need() evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL is returned. One can use this to check if a variable is valid. See ?need for more information.
I suggest defining a function like this:
is.valid <- function(x) {
require(shiny)
is.null(need(x, message = FALSE))
}
This function is.valid() will return FALSE if x is FALSE, NULL, NA, NaN, an empty string "", an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE, or an object of class try-error. In all other cases, it returns TRUE.
That means, need() (and is.valid()) covers a really broad range of failure cases. Instead of writing:
if (!is.null(x) && !is.na(x) && !is.nan(x)) {
...
}
one can write simply:
if (is.valid(x)) {
...
}
With the check for class try-error, it can even be used in conjunction with a try() block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)
bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
...
}