In R 3.0.2 the missing() function can tell us whether or not a formal parameter is missing.
How can one avoid hardcoding the variable name passed into missing? e.g. in
demoargs <- function(a=3, b=2, d) {
f <- formals(demoargs) # Capture formal arguments
formalNames <- names(f) # get variable names: a, b, d
...
}
I would like to be able to check for missing formals without doing this in a hardcoded manner, e.g.:
missing(formalNames[1]) # returns invalid use of missing!
as opposed to missing(d) for the purpose of iterating over a large number of optional arguments that are handled in a limited number of manners. I had hoped that get or as.name my put me on the right track but this does not seem to be the case.
Alternatively, I suspect that I could do this with the vararg arguments (...), but it would be nice for the caller to be able to inspect the acceptable optional arguments by examining the function declaration.
Thanks, Marie
In R the missing values are coded by the symbol NA . To identify missings in your dataset the function is is.na() . When you import dataset from other statistical applications the missing values might be coded with a number, for example 99 . In order to let R know that is a missing value you need to recode it.
In R, the easiest way to find columns that contain missing values is by combining the power of the functions is.na() and colSums(). First, you check and count the number of NA's per column. Then, you use a function such as names() or colnames() to return the names of the columns with at least one missing value.
First, if we want to exclude missing values from mathematical operations use the na. rm = TRUE argument. If you do not exclude these values most functions will return an NA . We may also desire to subset our data to obtain complete observations, those observations (rows) in our data that contain no missing data.
You probably first tried something like missing(as.name(formalNames[1]))
or missing(formalNames[1])
and found that they do not work.
The reason they don't is that missing()
is one of those odd functions -- library()
and debug()
are a couple of others -- that will accept as an argument either a name or a character representation of a name. That's 'nice' in the sense that missing(a)
and missing("a")
will both check whether the function call included a supplied argument a
; it's not so nice when you do missing(formalNames[1])
and it goes off to look for a non-existent argument named formalNames[1]
.
The solution is to use do.call()
, which evaluates the elements of its second argument before passing them on to the function given in its first argument. Here's what you might do:
demoargs <- function(a=3, b=2, d) {
formalNames <- names(formals()) # get variable names: a, b, d
do.call(missing, list(formalNames[1]))
}
## Try it out
demoargs(a=42)
# [1] FALSE
demoargs()
# [1] TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With