[R] Convert continuous variable into discrete variable
Dennis Murphy
djmuser at gmail.com
Sat Jul 16 00:13:49 CEST 2011
Hi:
x<-runif(100,0,100)
u <- cut(x, breaks = c(0, 3, 4.5, 6, 8, Inf), labels = c(1:5))
Based on the x I obtained,
> table(u)
u
1 2 3 4 5
3 2 1 2 92
cut() or findInterval() are the two basic functions for discretizing a
numeric variable.
HTH,
Dennis
On Fri, Jul 15, 2011 at 2:29 PM, Michael Haenlein
<haenlein at escpeurope.eu> wrote:
> Dear all,
>
> I have a continuous variable that can take on values between 0 and 100, for
> example: x<-runif(100,0,100)
>
> I also have a second variable that defines a series of thresholds, for
> example: y<-c(3, 4.5, 6, 8)
>
> I would like to convert my continuous variable into a discrete one using the
> threshold variables:
>
> If x is between 0 and 3 the discrete variable should be 1
> If x is between 3 and 4.5 the discrete variable should be 2
> If x is between 4.5 and 6 the discrete variable should be 3
> If x is between 6 and 8 the discrete variable should be 4
> If x is larger than 8 the discrete variable should be 5
>
> Is there a straightforward way of doing this (besides working with several
> if statements in a row)?
>
> Thanks,
>
> Michael
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list