1

I am very very new to R and programming in general and I am asking this question as part of a degree program. Don't worry, our professor said we could use StackOverflow. So here is my question: our first requirement is to create a function that returns TRUE or FALSE based on a passing grade score of 70. Here is my code for this:

passGrade <- function(x) {
 if(x>=70) {
  return('TRUE')
 }
 return('FALSE')
}

The second requirement is to use the results from this function and write a new function that will print "Congrats" is TRUE and "Try Harder!" if FALSE. It seems like I need to store the results of the first set of code as a variable, but when I do that it is not correctly read in the second code set. Here is my failed attempt

passGrade <- function(x) {
 if(x>=70) {
  x <- return('TRUE')
 }
 x <- return('FALSE')
}

Message <- function(x) {
 if(x == 'TRUE') {
  return("Congrats")
 }
 return("Try Harder!")
} 

I am sure there is a super simple solution to this, but I am not having any luck.

2
  • 2
    (1) Are you intending to return the strings of 'TRUE' and "FALSE", or the R native objects TRUE/FALSE? I suggest the latter, which is more idiomatic and efficient (imo). (2) Nested function calls are natural in any language, such as f(1) and g(...) can be combined as g(f(1)). What have you tried? What failed? Commented Oct 31, 2019 at 16:37
  • Other thoughts, hope you find them helpful: (1) no need to capture the return value from return, it immediately exits the function with its argument as the return value to the function, so x is ignored in passGrade. (2) if you agree that using strings should be changed to boolean objects, then passGrade <- function(x) return(x >= 70) (or just function(x) (x >= 70), since the last expression/value is automatically returned) is enough and much more idiomatic/succinct. Commented Oct 31, 2019 at 17:09

1 Answer 1

2

Below is a simple solution, you can directly return TRUE or FALSE based on the condition and then pass this to Message function to print out the required output, as shown below:

passGrade <- function(x) {
  if(x>=70) {
    return(TRUE)
  }
  return(FALSE)
}

Message <- function(x) {
  if(x == TRUE) {
    return("Congrats")
  }
  return("Try Harder!")
} 

Message(passGrade(60))
Message(passGrade(80))

Output:

[1] "Congrats"
[1] "Try Harder!"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.