-2

I have a column and I have a criteria. I want to write a function to see the value in that column fall into which category.

column:
Risk
0.493
1
2
1.7
1
1.7
0.29
0.493
2
0.493

criteria:
Low
0 0.517
Med
0.517 1.859
High
1.859 Inf

Desired output:
0.493   Low
1   Med
2   High
1.7 Med
1   Med
1.7 Med
0.29    Low
0.493   Low
2   High
0.493   Low

I tried to write a function but all come out to the category Med:

RiskCat <- function(x) {
for ( i in 1:length(x)){
if ( i <= 0.517 ) {
  print("Reduced")
} else if ( i > 0.517 & i <= 1.859 ){
    print("Med")
} else if ( i > 1.859 ) {
    print("High")
} } }

Thanks you for your advice! or may be somebody can correct my function as it runs, it always printed Med and I can't figure it out.

Peter Chung
  • 1,010
  • 1
  • 13
  • 31
  • @RonakShah actually I want to have a function , so that I can RiskCat(0.7) and it tells me it is Med, so it is not the same question at all, but you can say the concept is similar. – Peter Chung Oct 25 '16 at 09:51

1 Answers1

0

We can do this with cut

cut(df1$Risk, breaks = c(-Inf, 0.517, 1.859, Inf), labels = c("Low", "Med", "High"))
#[1] Low  Med  High Med  Med  Med  Low  Low  High Low 
#Levels: Low Med High
akrun
  • 874,273
  • 37
  • 540
  • 662