-1

I thought I had figured this one out. I have a variable called:

count_1

It's just a vector with one element. As I go through my loops, sometimes it has a value, and at other times it doesn't. All I want to do is ask if it contains anything, and if not, merely loop back around. Right now my script fails because when count_1 is empty, I get this:

missing value where TRUE/FALSE needed Execution halted

Here is my attempt so far:

if (exists("count_1"))
  { 
    #code#
  }
13
  • 1
    @RonakShah Hmm I think that would fail if there'd be not count_1. Either if (exists("count_1") && !is.na(count_1)) or two nested ifs.
    – lukeA
    Commented Aug 22, 2016 at 11:38
  • 1
    Actually the above code you had mentioned should work unless its na. If in loop just use else { next } that should work I guess. In fact I tried something similar and it worked- a <- 5 rm(b) if(a%%2 == 0 ) { b <- 1 } if(exists("b")) { print('hi') }else { print('bye') } Commented Aug 22, 2016 at 11:40
  • 1
    @zx8754 I believe their #code# contains some subsetting with a logical comparison or something similar.
    – Roland
    Commented Aug 22, 2016 at 11:41
  • 1
    @zx8754 Yes, and they are trying to avoid it with the if condition.
    – Roland
    Commented Aug 22, 2016 at 11:43
  • 2
    Never use exists for general code. This is a function to support infrastructure programming, it should simply never appear in normal analysis (or general user-level) code: if you write the code, you should know whether a variable exists. Asking the question inside the code is a sure sign that there’s a logic error in the code. Commented Aug 22, 2016 at 11:56

2 Answers 2

2

Use if(length(count_1) == 1) { next } to check if there is a value in count_1.

However, this will only work if your code does something like this:

dat <- 1:5
count_1 <- which(dat > 10)
count_1
# integer(0)
length(count_1) == 1
# [1] FALSE

It will not work with another way of filling the variable, e.g.:

count_1 <- ifelse(any(dat > 10), which(dat > 10), NA)
count_1
# [1] NA
length(count_1) == 1
# [1] TRUE
2
  • 2
    Suggestion: Maybe it would be good to combine the two possibilities, empty and NA values, like this: if (length(count_1) && !is.na(count_1))...
    – RHertel
    Commented Aug 22, 2016 at 12:07
  • @RHertel Absolutely. If we knew who the OP creates the variable, we could provide a bullet-proof solution.
    – nya
    Commented Aug 22, 2016 at 12:08
2

For a different reason, I need to check if a variable exists inside a function. I use this:

check=function(x) tryCatch(if(class(x) == 'logical') 1 else 1, error=function(e) 0) 
varX=1 
check(varX)
[1] 1
rm(varX)
check(varX)
[1] 0
f1= function(x) if(check(x)) cat('exists') else cat('not exists')
f1(varX)
not exists

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.