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
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.