1

How to change the level names of a set of factor?
Please check the F1 of Example df , F1 is a factor of 6 levels(0~5).

How do I change F1 into 3 levels(1,2,3)?

eg: if F1 == 0 or 1, the new level name is 1, if F1 == 2 or 3, the new level name is 2, if F1 == 4 or 5, the new level name is 3. Like Expected Outcome.

library(plyr)
revalue(df$F1, c("0"="1", "1"="1","2"="2", "3"="2","4"="3", "5"="3"))
# I could do this but if there are tens or hundreds of levels, 
# I will need to do this one by one, there must be a more convenient way.  

Example df

    Volume Weight F1 F2 
 1: 0.5367 0.5367  0  1
 2: 0.8645 0.8508  0  0
 3: 0.8573 0.8585  0  0
 4: 1.1457 1.1413  1  0
 5: 0.8573 0.8568  1  0
 6: 0.5694 0.5633  1  1
 7: 1.2368 1.2343  2  0
 8: 0.9662 0.9593  2  1
 9: 1.4850 1.3412  2  0
10: 1.4850 1.3995  2  0
11: 1.1132 1.1069  3  1
12: 1.4535 1.3923  3  0
13: 1.0437 1.0344  3  1
14: 1.1475 1.1447  4  1
15: 1.1859 1.1748  4  0
16: 1.1859 1.1735  4  0
17: 1.1859 1.1731  4  0
18: 1.1557 1.1552  5  1
19: 1.1749 1.1731  5  0
20: 1.1749 1.1552  5  0

Expected Outcome

   Volume Weight F1 F2 
 1: 0.5367 0.5367  1  1
 2: 0.8645 0.8508  1  0
 3: 0.8573 0.8585  1  0
 4: 1.1457 1.1413  1  0
 5: 0.8573 0.8568  1  0
 6: 0.5694 0.5633  1  1
 7: 1.2368 1.2343  2  0
 8: 0.9662 0.9593  2  1
 9: 1.4850 1.3412  2  0
10: 1.4850 1.3995  2  0
11: 1.1132 1.1069  2  1
12: 1.4535 1.3923  2  0
13: 1.0437 1.0344  2  1
14: 1.1475 1.1447  3  1
15: 1.1859 1.1748  3  0
16: 1.1859 1.1735  3  0
17: 1.1859 1.1731  3  0
18: 1.1557 1.1552  3  1
19: 1.1749 1.1731  3  0
20: 1.1749 1.1552  3  0
Jimmy
  • 427
  • 2
  • 16
  • 1
    If there are tens or hundreds of levels, what's the rule for how to recode them? Lowest level as `1`, and then every two values after that collapsed together, so `2 + 3`, `4 + 5`, `6 + 7`, etc.? If the question is about how to scale this up to large numbers of levels, you need to explain the rule. – Marius Jun 01 '17 at 05:31
  • 2
    How about `df$F1 <- factor(1 + as.numeric(df$F1) %/% 2)` – Andrew Gustar Jun 01 '17 at 05:39
  • 2
    Or: `df[, F1 := floor(F1 / 2) + 1 ]` – Jaap Jun 01 '17 at 06:28

1 Answers1

2

We can use data.table methods as the object is a data.table

library(data.table)
df[, F1 := factor((F1 %/% 2)+1)]
akrun
  • 874,273
  • 37
  • 540
  • 662