1

Is there a way how to check if value exists in R environment and if == TRUE, assign this existing value otherwise assign something else?

In other words, I have nothing in my R right now and I created this if else statement.

test <- if_else(exists("my_value"), my_value, "my value missing, assigning this string")

Result of

 exists("my_value")

is:

exists("my_value")
[1] FALSE

But once I run whole code I get this

Error in if_else(exists("my_value"), my_value, "my value missing, assigning this string") : object 'my_value' not found

Cath
  • 23,906
  • 5
  • 52
  • 86
  • 1
    Try doing `ls()`. It will show you all objects you have defined in your global env. – Sotos Jul 02 '19 at 09:03
  • 2
    If you use `ifelse` instead of `if_else` it should work. – Ronak Shah Jul 02 '19 at 09:07
  • if `my_value` does not exist, after your statement, `test` will exist but `my_value` still won't – Cath Jul 02 '19 at 09:08
  • 1
    This isn't really a duplicate, since the problem here is that OP is misusing `if_else` – Hong Ooi Jul 02 '19 at 09:21
  • @HongOoi true, I reopened, though title is misleading imo. also, as `if_else` is not base R, tag of corresponding package should be included.... – Cath Jul 02 '19 at 09:40
  • 1
    I guess the question is "how do I do this with `dplyr::if_else`?" – zx8754 Jul 02 '19 at 09:53
  • 2
    @zx8754 The answer should be "use `if() ... else ...`", since that is the control flow statement, not ifelse or if_else. – Hong Ooi Jul 02 '19 at 10:41
  • @HongOoi Yes, agree, I was just composing the answer. Internet failed on me... so a bit of a delay. – zx8754 Jul 02 '19 at 10:49

1 Answers1

3

if() {} else {} is more suitable for this case:

if(exists("my_value")){ 
  test <- my_value } else { 
    test <- "my value missing, assigning this string"}

Using dplyr::if_else(condition, true, false, missing = NULL) won't work as it is checking the values for true and false are of the same length, class, type, hence the error.

I am guessing it could be done with if_else, if we manage to make values for true and false of the same class somehow.

zx8754
  • 52,746
  • 12
  • 114
  • 209