简体   繁体   English

如何将数字变量重新编码为分类?

[英]How to recode numerical variable into categorical?

Hi I've been trying to recode numerical variables into categorical. 嗨,我一直在尝试将数字变量重新编码为分类变量。

For example, using mtcars , I am trying to divide mpg into 2 category < 25 & =>25 例如,使用mtcars ,我试图将mpg分为2类<25&=> 25

These are the codes that I've tried, but getting error message. 这些是我尝试过的代码,但收到错误消息。

data=mtcars
summary(mtcars$mpg)
Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
10.40   15.43   19.20   20.09   22.80   33.90 

mpgcat <- cut(mpg, breaks = (0,24.99,34), labels = c("0","1"))

Error: unexpected ',' in "mpgcat <- cut(mpg, breaks = (0," 错误:“ mpgcat <-cut(mpg,breaks =(0,”

cut divides the range of x into intervals and codes the values in x according to which interval they fall. cutx的范围划分为间隔,并根据x的值落入的间隔对其进行编码。 The leftmost interval corresponds to level one, the next leftmost to level two and so on. 最左边的间隔对应于级别1,下一个最左边的间隔对应于级别2,依此类推。

breaks is either a numeric vector of two or more unique cut points or a single number (greater than or equal to 2) giving the number of intervals into which x is to be cut. breaks是两个或多个唯一切割点的数值向量,或者是一个单个数字(大于或等于2),给出要切割的x的间隔数。

So you'll need some script code eg: 因此,您需要一些脚本代码,例如:

data=mtcars
summary(mtcars$mpg)
mpgcut <- cut(mtcars$mpg, breaks = c(0,24.99,34), labels = c("0","1"))
mpgcut

to get a result like this: 得到这样的结果:

[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0
Levels: 0 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM