0

The data.table DT has the following structure. Note that region_code is a factor with 4 levels. I want to change those levels.

Classes ‘data.table’ and 'data.frame':  28 obs. of  4 variables:
 $ scenario   : chr  "2010" "SSP2-NoCC" "SSP1-NoCC" "SSP3-NoCC" ...
 $ region_code: Factor w/ 4 levels "highInc","lowInc",..: 2 2 2 2 2 2 2 3 3 3 ...
 $ region_name: chr  "Low income" "Low income" "Low income" "Low income" ...
 $ value      : num  17.8 18.6 20.1 17.9 18.3 ...
 - attr(*, ".internal.selfref")=<externalptr> 

Here is the output of head(DT) before I try to change the order of the levels.

    scenario region_code region_name    value
1:      2010      lowInc  Low income 17.76127
2: SSP2-NoCC      lowInc  Low income 18.55630
3: SSP1-NoCC      lowInc  Low income 20.08646
4: SSP3-NoCC      lowInc  Low income 17.87970
5: SSP2-GFDL      lowInc  Low income 18.30423
6: SSP2-IPSL      lowInc  Low income 18.36362

Then I try to change the order of the levels of region_code with

levels(DT$region_code) <- c("lowInc", "lowMidInc", "upMidInc", "highInc")

Now the output of head(DT) is

    scenario region_code region_name    value
1:      2010   lowMidInc  Low income 17.76127
2: SSP2-NoCC   lowMidInc  Low income 18.55630
3: SSP1-NoCC   lowMidInc  Low income 20.08646
4: SSP3-NoCC   lowMidInc  Low income 17.87970
5: SSP2-GFDL   lowMidInc  Low income 18.30423
6: SSP2-IPSL   lowMidInc  Low income 18.36362

Note that for example the first row's value of region_code has been changed lowMidInc but all other elements are the same.

How do I keep the row contents the same and just change the level attribute for the region_code column?

JerryN
  • 2,356
  • 1
  • 15
  • 49
  • 3
    I'm not sure this has anything to do with data.table. If I do `f = factor(c("C","A","B","D")); levels(f) = rev(levels(f))`, the labels are overwritten in the same way. I think you probably want something like `DT[, f := factor(f, levels = new_levels)]` per http://stackoverflow.com/q/2375587/ – Frank Jan 16 '17 at 17:21
  • 1
    That works. Thanks! Data.table was the only keyword that SO would let me use. – JerryN Jan 16 '17 at 17:37

0 Answers0