-3

I have two variables with the following levels: 1, 2, and 3. I averaged them together so now the levels are:

Levels: 0 < .5 < 1 < 1.5 < 2 < 2.5 < 3

However, I need to collapse .5 with 1, 1.5 with 2, and 2.5 with 3. Would the easiest solution bet to use factor recode? The syntax does not appear to make sense to me.

Nick
  • 25
  • 5
  • 2
    If it's a simple vector, I'd think `round` would do it. If you have `factor` bins of data, then it'll be something else. Please provide sample data; this has been suggested before to your questions, please see (https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info) for suggestions on doing this well. While you're at it, please consider [accepting past answers](https://stackoverflow.com/help/someone-answers). – r2evans Jan 01 '21 at 21:13
  • 1
    I'm very new to R. I will try these suggestions. Please do not interpret my lack of doing these to be disrespect. – Nick Jan 02 '21 at 01:11

1 Answers1

0

You seem to have an ordered factor.

x <- factor(c(.5, 1, 1.5, 2, 2.5, 3), ordered = TRUE)
x

#[1] 0.5 1   1.5 2   2.5 3  
#Levels: 0.5 < 1 < 1.5 < 2 < 2.5 < 3

You can convert them to numeric and use ceiling to combine 0.5 with 1, 1.5 with 2 and so on.

y <- factor(ceiling(as.numeric(as.character(x))), ordered = TRUE)
y
#[1] 1 1 2 2 3 3
#Levels: 1 < 2 < 3

Another option is to collapse the factor explicitly using fct_collapse from forcats.

y <- forcats::fct_collapse(x, "1" = c("0.5", "1"), 
                              "2" = c("1.5", "2"), 
                              "3" = c("2.5", "3"))
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178