R create factor based on condition

后端 未结 1 1297
花落未央
花落未央 2021-01-05 23:35

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 &         


        
1条回答
  •  抹茶落季
    2021-01-06 00:15

    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"))
    

    0 讨论(0)
提交回复
热议问题