Search code examples
rquotes

remove quote from output of conditional sentence in r


I have several conditional statements for my data and I got the desired value within a quote. I want to remove this quote but I cannot.

dd <- function(x){
if ( (x >= 15& x <= 19)) {print ("4")}
else if ( (x >= 20& x <= 29)) {print ("5")}
if ( (x >= 30& x <= 39)) {print ("6")}
else if ( (x >= 40& x <= 45)) {print ("7")}
if ( (x >= 46& x <= 50)) {print ("8")}
else if ( (x >= 51& x <= 55)) {print ("9")}
if ( (x >= 56& x <= 60)) {print ("10")}
else if ( (x >= 61& x <= 70)) {print ("11")}
}


>dd(55) 
[1] "9"

My desired value is 9. I want this value without quote which can be expressed by a letter like this

> k
[1] 9 

I used this code but I failed.

 print(dd(55), quote=FALSE)

So, I need help. Thanks in advance.


Solution

  • In your code, you have used print with character values of numbers hence you are recieving quotes. Also you should use return instead of print.

    Of course cut or findInverval is way better option than below, I am just putting it for simplicity and continuing with your approach.

    How does it work: Since every condition is mutually exclusive, two things can't be true at same instance, a TRUE value in R when multiplied it(TRUE) coerces to 1 and hence 1 getting multiplied with your coefficient value. However, wherever the situation doesn't satisfies, the value calculated as FALSE, which coerces to zero, which when multiplied with your coefficient returns zero. By this logic this should work in your case.

    dd <- function(x){
      return((x >= 15 & x <= 19)*4+ (x >= 20 & x <= 29)*5+ (x >= 30 & x <= 39)*6+ (x >= 40 & x <= 45)*7+ (x >= 46 & x <= 50)*8+ (x >= 51 & x <= 55)*9+ (x >= 56 & x <= 60)*10+ (x >= 61 & x <= 70)*11)
    }
    

    Output:

    > dd(17)
    [1] 4
    > dd(55)
    [1] 9
    >