KapitanPilips
KapitanPilips

Reputation: 31

Why does my variable with a message function result to a NULL?

The task I was assigned was to create an R program where the input is any numerical value and the output is whether the numeric is positive or negative. The conditions I had were to use either the message or cat functions for it. The problem is when I callback "sign_assign" by itself it returns a NULL. But when I callback the same variable along with the instructions it shows the message properly. Thank you!

 x <- 0 
   sign_assign <- if(x>0){
      message(x," is positive")   
      } else if(x<0){
      message(x," is negative")   
      } else{
      stop("0 not positive nor negative")   
}

Here is the input and output I need for the program: Input: x <- -6; Output: -6 is negative

P.S. What I meant by "callback the same variable along with the instructions" is to run "sign_assign" along with the if statements. Sorry if I seem confusing I am new in programming R!

Upvotes: 0

Views: 111

Answers (1)

AndrewGB
AndrewGB

Reputation: 16856

As others have suggested, cat and message are not good choices here. You can make sign_assign a function, then return a character vector for the positive or negative number.

sign_assign <- function(x) {
  if (x > 0) {
    return(paste0(x, " is positive"))
  } else if (x < 0) {
    return(paste0(x, " is negative"))
  } else{
    stop("0 not positive nor negative")
  }
}

Examples

sign_assign(-6)
[1] "-6 is negative"

sign_assign(4)
[1] "4 is positive"

sign_assign(0)
Error in sign_assign(0): 0 not positive nor negative

The upside of creating a function is that you could then apply this function to a list of numbers. However, you would need an alternative to using stop. So, you could either return a message for non-positive/negative numbers or an NA or something else.

library(purrr)

sign_assign2 <- function(x) {
  if (x > 0) {
    return(paste0(x, " is positive"))
  } else if (x < 0) {
    return(paste0(x, " is negative"))
  } else{
    return("value not positive nor negative")
  }
}

numbers <- c(-6, 3, 2, -100, 84, 0, 60)

numbers_output <- purrr::map(numbers, sign_assign2)

Output

[[1]]
[1] "-6 is negative"

[[2]]
[1] "3 is positive"

[[3]]
[1] "2 is positive"

[[4]]
[1] "-100 is negative"

[[5]]
[1] "84 is positive"

[[6]]
[1] "value not positive nor negative"

[[7]]
[1] "60 is positive"

Upvotes: 1

Related Questions