[R] Checking if a logical variable exists

Duncan Murdoch murdoch.duncan at gmail.com
Sun Dec 14 14:43:11 CET 2014


On 14/12/2014, 8:07 AM, Steven Yen wrote:
> My obj does not always come with a logical variable defined. So I do
> 
> my.foo <- function(obj,df,digits=5){
> if (!is.na("obj$spec$Fisher")) Fisher<-obj$spec$Fisher
> ...
> }
> 
> This works when "Fisher" is defined in/passed from obj. When it is 
> not, I get error:
> 
> Error in (!is.na("obj$spec$Fisher")) & Fisher :
>    operations are possible only for numeric, logical or complex types
> 
> I tried exist(Fisher), missing(Fisher)... to no vail. Any idea? Thanks.

The test you want is based on is.null(), and you definitely don't want
quotes there.  For example,

if (!is.null(obj$spec) && !is.null(obj$spec$Fisher))
  Fisher <- obj$spec$Fisher

Duncan Murdoch



More information about the R-help mailing list