0
votes

I have a continuous variable that I would like to turn into a factor.

The data is:

DCA<-c(0.14,0.14,0.16,0.16,0.27,0.27,0.07,0.07,0.41,0.41,0.00,0.00,0.33,0.33,0.11,0.11,0.64,0.64,0.28,0.28,0.02,0.02,0.43,0.43,0.24,0.24,0.08,0.08,0.00,0.00,0.64,0.64,0.07,0.07,0.16,0.16,0.24,0.24,0.26,0.26,0.64,0.64,0.22,0.22,0.03,0.03,0.03,0.03,0.35,0.35,0.35,0.35,0.37,0.37,0.37,0.37,0.22,0.22,0.00,0.00,0.33,0.33,0.19,0.19,0.33,0.33,0.33,0.33,0.02,0.02,0.36,0.36)

I know that you can do this quickly with

DCA.f<-factor(DCA)

but this creates factors for every unique value. I want to specify the factor levels so that the levels are

0, less than or equal to 0.10, greater than 0.10 and less than or equal to 0.20, and so on and so on until greater than 0.50.

I think this will have to be specified in the "levels" in the factor function but I don't know how to specify what I describe above.

1

1 Answers

2
votes

Look into cut:

cut(DCA, c(-Inf, seq(0, .5, .1), Inf))
#  [1] (0.1,0.2]  (0.1,0.2]  (0.1,0.2]  (0.1,0.2]  (0.2,0.3]  (0.2,0.3]  (0,0.1]   
#  [8] (0,0.1]    (0.4,0.5]  (0.4,0.5]  (-Inf,0]   (-Inf,0]   (0.3,0.4]  (0.3,0.4] 
# [15] (0.1,0.2]  (0.1,0.2]  (0.5, Inf] (0.5, Inf] (0.2,0.3]  (0.2,0.3]  (0,0.1]   
# [22] (0,0.1]    (0.4,0.5]  (0.4,0.5]  (0.2,0.3]  (0.2,0.3]  (0,0.1]    (0,0.1]   
# [29] (-Inf,0]   (-Inf,0]   (0.5, Inf] (0.5, Inf] (0,0.1]    (0,0.1]    (0.1,0.2] 
# [36] (0.1,0.2]  (0.2,0.3]  (0.2,0.3]  (0.2,0.3]  (0.2,0.3]  (0.5, Inf] (0.5, Inf]
# [43] (0.2,0.3]  (0.2,0.3]  (0,0.1]    (0,0.1]    (0,0.1]    (0,0.1]    (0.3,0.4] 
# [50] (0.3,0.4]  (0.3,0.4]  (0.3,0.4]  (0.3,0.4]  (0.3,0.4]  (0.3,0.4]  (0.3,0.4] 
# [57] (0.2,0.3]  (0.2,0.3]  (-Inf,0]   (-Inf,0]   (0.3,0.4]  (0.3,0.4]  (0.1,0.2] 
# [64] (0.1,0.2]  (0.3,0.4]  (0.3,0.4]  (0.3,0.4]  (0.3,0.4]  (0,0.1]    (0,0.1]   
# [71] (0.3,0.4]  (0.3,0.4] 
# 7 Levels: (-Inf,0] (0,0.1] (0.1,0.2] (0.2,0.3] (0.3,0.4] ... (0.5, Inf]

You may want to customize the second argument ("breaks") to represent the breaks you are actually looking for as well as look into some of the other arguments that can be passed to the cut function.