Anandapadmanathan
Anandapadmanathan

Reputation: 355

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

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

Upvotes: 1

Views: 619

Answers (1)

help-info.de
help-info.de

Reputation: 7298

cut divides the range of x into intervals and codes the values in x according to which interval they fall. The leftmost interval corresponds to level one, the next leftmost to level two and so on.

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.

So you'll need some script code e.g.:

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

Upvotes: 2

Related Questions