Peter Chung Peter Chung - 1 month ago 6
R Question

R write function to generate a new column

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!

Answer

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