Home > OS >  if...else (with exists()) in R function returning "unused argument" error
if...else (with exists()) in R function returning "unused argument" error

Time:03-10

I am trying to learn to make different variations of basic functions on my own. However, despite my test statement defining "x" within if, the returning results did not execute the else correctly. I googled various tutorial sites such as DataCamp and Khan. The syntax, from what I can see, is correct. Was hoping someone out there may see differently and could explain why?

p <- function() {
  if (!exists("x")) {
    x <- "there is no number"
  } else {
    x <- "what do you want to add?"
  }
  x
}

Below is the screen shot of my console: function with returning Error "Error in p(4) : unused argument (4)"

Various attempts:

  • I tried removing the "x" framing in my exists() but when I try to run p() , I get a Error in exists(x) : object 'x' not found and with p(4), it returned a Error in p(4) : unused argument (4)
  • I adjusted p <- function(x) as well, but then received for p() an Error in exists(x) : argument "x" is missing, with no default With p(4), an Error in exists(x) : invalid first argument
  • Removing the ! negation in exists() yielded a p() return of "what do you want to add?" and with p(4) an Error in p(4) : unused argument (4) again.

Should I not use exists() within the test statement after all? Did I make this unnecessarily complicated on myself?

Anna

CodePudding user response:

So you definitely need to have an argument in your function. Plus I don't think you have to do all that assigning within the if/else statements. I think this gets what you're looking for, but not sure:

p <- function(some_object) {
  if (!exists(some_object)) {
    "there is no number"
  } else
    "what do you want to add?"
}

x <- 1   1

p("x")

CodePudding user response:

It looks like a collaboration of both Bill and Ben's answers worked!

I gave up on using exists() and tabled it to master on another day. Meantime, with both codes merged, I got this:

p <- function(x) {
  if (missing(x)) {
    "there is no number"
  } else
    "what do you want to add?"
}

missing() was definitely a far friendlier function to use. I achieved the results I aimed for. p() returned a "there is no number" and p(4) returned a "what do you want to add?" At last!

Thank you both for helping me tackling what I thought was going to be a simple function. Clearly not! I'm going to tackle missing() and exists() ad nauseum and master this.

Much gratitude for the advice! I'm going to post the answer here in case another encounters the same snag.

Gratefully Yours, Anna

  • Related