Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the order of some data frame columns

Tags:

dataframe

r

apply

I have a data.frame and I want to calculate a performance metric (e.g. a quantile). However some columns of the data.frame are with statistics that you would consider "negative" - an example:

r=seq(0,1,0.25)
apply(state.x77,2,function(x) quantile(x,probs = r))
     Population  Income Illiteracy Life Exp Murder HS Grad  Frost      Area
0%        365.0 3098.00      0.500  67.9600  1.400   37.80   0.00   1049.00
25%      1079.5 3992.75      0.625  70.1175  4.350   48.05  66.25  36985.25
50%      2838.5 4519.00      0.950  70.6750  6.850   53.25 114.50  54277.00
75%      4968.5 4813.50      1.575  71.8925 10.675   59.15 139.75  81162.50
100%    21198.0 6315.00      2.800  73.6000 15.100   67.30 188.00 566432.00

Income and life expectancy are positive. However, e.g. the murder rate is negative, the lower it is the better. I want exactly this result:

     Population  Income Illiteracy Life Exp Murder HS Grad  Frost      Area
0%        365.0 3098.00      2.800  67.9600 15.100   37.80 188.00   1049.00
25%      1079.5 3992.75      1.575  70.1175 10.675   48.05 139.75  36985.25
50%      2838.5 4519.00      0.950  70.6750  6.850   53.25 114.50  54277.00
75%      4968.5 4813.50      0.625  71.8925  4.350   59.15  66.25  81162.50
100%    21198.0 6315.00      0.500  73.6000  1.400   67.30   0.00 566432.00

I managed that using two sweep-functions and one apply function. That is ugly as heck! Is there a more elegant way?

The dataset state.x77 is built-into R.

like image 924
5th Avatar asked Sep 18 '25 04:09

5th


1 Answers

You can multiply each column by the respective weight in vector my_weight. Then take the absolute value of the result. And there is no need to define a vector of probabilities since the quartiles are already quantile's default.

my_weight <- c(1, 1, -1, 1, -1, 1, -1, 1)
res <- sapply(seq_along(as.data.frame(state.x77)), function(i)
  abs(quantile(state.x77[, i]* my_weight[i])))
colnames(res) <- colnames(state.x77)

res
#     Population  Income Illiteracy Life Exp Murder HS Grad  Frost      Area
#0%        365.0 3098.00      2.800  67.9600 15.100   37.80 188.00   1049.00
#25%      1079.5 3992.75      1.575  70.1175 10.675   48.05 139.75  36985.25
#50%      2838.5 4519.00      0.950  70.6750  6.850   53.25 114.50  54277.00
#75%      4968.5 4813.50      0.625  71.8925  4.350   59.15  66.25  81162.50
#100%    21198.0 6315.00      0.500  73.6000  1.400   67.30   0.00 566432.00
like image 149
Rui Barradas Avatar answered Sep 19 '25 20:09

Rui Barradas