Home > Mobile >  Is there any alternative for this R language problem
Is there any alternative for this R language problem

Time:12-09

Question -> Build a condition to check if all the numbers in the vector marks (passed as arguments) are greater than 90. If yes, assign the string "Best Class" to the variable ans, else assign "Needs Improvement"

Answer ->

classmark<-function (marks) { # Enter your code here. Read input from STDIN. Print output

ans<-ifelse (c(marks) >90, "Best Class", "Needs Improvement")

return(ans)

}

print(classmark (c(100,95,94,56))) 
print(classmark (c(100,95,94,96)))

Output :

[1] "Best Class" "Best Class" "Best Class" [4] "Needs Improvement"

[1] "Best Class" "Best Class" "Best Class" "Best Class"

Complied successfully But no test cases passed It shows hidden test cases are failing

CodePudding user response:

You are being asked to check if all the numbers in the vector are greater than 90. Here you can lean on the fact that TRUE will evaluate to 1, and FALSE to 0. As such, you can check if the sum of the TRUE cases are equal to the length of the input. If this is the case, all marks are greater than 90.

Also note that it is not necessary to explicitly call return in R, but I included it to match your attempt more closely.

As for reading from STDIN, I will leave that part for you to figure out, as this is likely homework.

classmark <- function(marks) {
  
  pass = ifelse(marks > 90, TRUE, FALSE)
  
  ans = ifelse(sum(pass) == length(marks), "Best class", "Needs improvement")
  return(ans)
}

classmark(c(100, 95, 91))
#> [1] "Best class"
classmark(c(100, 95, 80))
#> [1] "Needs improvement"

Alternatively you can accomplish the same task with all, which checks if all conditions are met:

classmark <- function(marks) {
  
  ans = ifelse(all(marks > 90), "Best class", "Needs improvement")
  return(ans)
}

classmark(c(100, 95, 91))
#> [1] "Best class"
classmark(c(100, 95, 80))
#> [1] "Needs improvement"

Created on 2021-12-09 by the reprex package (v0.3.0)

CodePudding user response:

As we are doing your homework here ;) It is not asked for a function, so there is no need for that.

This would suffice to meet all criteria given in the question.

marks <- c(100, 95, 94, 56)
ans <- ifelse(any(marks <= 90), "Needs Improvement", "Best Class")
  •  Tags:  
  • r
  • Related