This question already has answers here:
Add column which contains binned values of an integer column

(3 个回答)


8 个月前关闭。




我正在尝试将一组变量转换为因子变量:
可变质量示例,值是:3,4,5,6,7,8,9我想要一个新的 FACTORED 变量 qual_level ,它具有低、中和高的值,使得
low <- quality(3,4)
medium<- quality(5,6,7)
high<- quality(8,9)

因此我尝试实现以下代码。
q_levels <-  a <- factor (white_wine$quality ,
                      c(3,4,5.6,7,8,9,10),
                      levels=1:3,
                      labels=c("Low",  "Medium", "High"))

上面的代码抛出一个错误:
Error in factor(white_wine$quality, c(3, 4, 5.6, 7, 8, 9, 10), levels = 1:3, : invalid 'labels'; length 3 should be 1 or 2

如何改进代码?

最佳答案

使用 cut 离散化连续变量:

x <- c(3,4,5,6,7,8,9)
cut(x, c(-Inf, 4, 7, 9), labels = c("Low",  "Medium", "High"))
#[1] Low    Low    Medium Medium Medium High   High
#Levels: Low Medium High

关于r - 将数值向量转换为因子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46278457/

10-12 23:30