Selrac Selrac - 2 months ago 6
R Question

R create factor based on condition

I need to change a column from numeric to factor based on the numeric value being higher or lower than 10.

For example with the following data:

age <- c(1:20)
hight <- c(1:20)
d.frame <- data.frame(age, hight)


I tried the following:

d.frame$hight <- factor(d.frame$hight, levels( 1:9, 10:max(d.frame$hight) ), labels=c('low','high'))


and

d.frame$hight <- factor(d.frame$hight, levels( <10, >=10) ), labels=c('low','high'))


But don't work.

Any ideas now to do this type conversion?

Thanks

Answer

We could use cut to change the numeric to factor column based on the condition

d.frame$hight <- cut(d.frame$hight, breaks = c(-Inf, 10, Inf), 
             labels = c('low', 'high'), right = FALSE)

As there are only two levels, another option would be to create a logical vector and use ifelse to change the values

d.frame$hight <- factor(ifelse(d.frame$hight>=10, "high", "low"))
Comments