Home > Net >  Sort dataframe by row index value without changing values
Sort dataframe by row index value without changing values

Time:07-23

I have a dataframe that I have to sort in decreasing order of absolute row value without changing the actual values (some of which are negative).

To give you an example, e.g. for the 1st row, I would like to go from
-0.01189179 0.03687456 -0.12202753 to
-0.12202753 0.03687456 -0.01189179.
For the 2nd row from
-0.04220260 0.04129326 -0.07178175 to
-0.07178175 -0.04220260 0.04129326 etc.

How can I do this in R?

Many thanks!

CodePudding user response:

Try this

lst <- lapply(df , \(x) order(-abs(x)))

ans <- data.frame(Map(\(x,y) x[y] , df ,lst))
  • output
            a           b
1 -0.01189179 -0.07178175
2  0.03687456 -0.04220260
3 -0.12202753  0.04129326
  • data
df <- structure(list(a = c(-0.12202753, 0.03687456, -0.01189179), b = c(-0.0422026, 
0.04129326, -0.07178175)), row.names = c(NA, -3L), class = "data.frame")

CodePudding user response:

Here is a simple approach (using @Mohamed Desouky's Data)

df <- df[nrow(df):1,]
> df
            a           b
3 -0.01189179 -0.07178175
2  0.03687456  0.04129326
1 -0.12202753 -0.04220260
  • Related