Input parameters are not being recognized. No error message

With or without the quotes in is.numeric("y"), the function z always outputs the error message. The parameters are not being passed.

What is going on here?

> y=df[,1]
> y
 [1] 5 5 5 6 6 6 6 5 6 6 6 6 5 5 5 5
> class(y) #numeric
[1] "numeric"
> 
> z <- function(i,y){
+ i=i
+ y=y
+ flag=0
+ if(is.numeric("y")=="TRUE"){   
+ mean(y)/100
+ flag=1
+ flag}
+ if(is.integer("y")=="TRUE"){
+ mean(y)/100
+ flag=1
+ flag}
+ if(flag==0){
+ cat("output error message\n")}
+ }
> 
> z(1,fsalesP)

output error message

Hi @mmarion,

The value "y" in quotations is a string (or length 1 character vector, but thats besides the point). The object y without quotations is a numeric vector containing those numbers you assigned to that name. So you should refer to y without the quotations in this case.

Next, the is.numeric() function returns a TRUE or FALSE logical value. Also, you don't need the added condition of equality in your if() statements, since the is.numeric() already return the TRUE or FALSE logicals.

Try this:

z <- function(i, y) {
  i = i
  flag = 0
  
  if(is.numeric(y)) {   
  mean(y) / 100
  flag = 1
  flag
  }
  if(is.integer(y)) {
  mean(y) / 100
  flag = 1
  flag
  }
  if(flag==0) {
  cat("output error message\n")
  }
}

Note that this function has some odd habits. Integers are numeric, but not all numerics are integers. Consider some else statements to clean up the flow, unless this is the desired behaviour. The last object in a function gets returned (unless you call an explicit return(), so think about what you want this function to return to the user.

1 Like

Thanks. This function is extending my knowledge about R greatly. I made your suggested changes and it runs now for y = a single variable. y may be a vector and I need to make a list. That will take some thought.

About the cat function how do I get the value of i to be included in cat("output error message\n")? When I add it, it does not evaluate so I get "i output error message".

Hi @mmarion,

You may want to use stop(), warning(), or message() in place of cat() depending on the warning-level and behaviour you want. stop() is the most strict, it prints a message and halts execution of the action. The other two are less strict. To include a value in your message, try this:

i <- 10

cat(i, "here is the rest of the message")
message(i, " here is the rest of the message")
warning(i, " here is the rest of the message")
stop(i, " here is the rest of the message")
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.