How to factorize a numeric column into user-defined intervals

83 Views Asked by At

I am interested in factorizing a numeric column into say 3 factors. What I did is to subset the column into 3 range of intervals and then try to factorize the 3 intervals into a single column Z and finally, merge the new factor column Z into my original data frame but my idea is not working. Is there a smatter way to just factorize a numeric column into arbitrary number of factors so that the data frame will not be distorted?

set.seed(0)
df1 <- data.frame(Y =floor(runif(10, min=0, max=10)), 
                 X =floor(runif(10, min=0, max=50)))
 str(df1)
'data.frame':   10 obs. of  2 variables:
 $ Y: num  8 2 3 5 9 2 8 9 6 6
 $ X: num  3 10 8 34 19 38 24 35 49 19

# The intended three factor intervals: X=3, 4<=X<=30, X>30
df1$fac1 <- factor(df1$X == 3, label=c(0,1))
df1$fac2 <- factor(df1$X >= 4 & df1$X <= 30, label=c(0,1))
df1$fac3 <- factor(df1$X > 30, label=c(0,1))
head(df1)
str(df1)

df2 = cbind(df1$Y, df1$X1, df1$X2, df1$X3)

Warning messages:
1: In xtfrm.data.frame(x) : cannot xtfrm data frames
2: In xtfrm.data.frame(x) : cannot xtfrm data frames
3: In xtfrm.data.frame(x) : cannot xtfrm data frames

head(df2,3)
     [,1] [,2] [,3] [,4]
[1,]    8    2    2    2
[2,]    2    1    1    1
[3,]    3    2    2    2

However, even if this works, I suspect this could distort the rows of my original df1. What I really want is to make X a one column factor with 3 levels using the given intervals.

2

There are 2 best solutions below

1
YH Jang On

You can use factor().

df1$fac1 <- factor(df1$X == 3, label=c(0,1))
df1$fac2 <- factor(df1$X >= 4 & df1$X <= 30, label=c(0,1))
df1$fac3 <- factor(df1$X > 30, label=c(0,1))

output

   Y  X fac1 fac2 fac3
1  8  3    1    0    0
2  2 10    0    1    0
3  3  8    0    1    0
4  5 34    0    0    1
5  9 19    0    1    0
6  2 38    0    0    1
7  8 24    0    1    0
8  9 35    0    0    1
9  6 49    0    0    1
10 6 19    0    1    0
1
L Tyrone On

There are many options, but cut() is probably the best in this case:

# Your data
set.seed(0)
df1 <- data.frame(Y = floor(runif(10, min=0, max=10)), 
                  X = floor(runif(10, min=0, max=50)))


df1$Z <- cut(df1$X, c(0, 3, 30, Inf), labels = c(1:3), ordered_result = TRUE)
df1
#    Y  X Z
# 1  8  3 1
# 2  2 10 2
# 3  3  8 2
# 4  5 34 3
# 5  9 19 2
# 6  2 38 3
# 7  8 24 2
# 8  9 35 3
# 9  6 49 3
# 10 6 19 2

str(df1)
# 'data.frame': 10 obs. of  3 variables:
#   $ Y: num  8 2 3 5 9 2 8 9 6 6
# $ X: num  3 10 8 34 19 38 24 35 49 19
# $ Z: Ord.factor w/ 3 levels "1"<"2"<"3": 1 2 2 3 2 3 2 3 3 2