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?