Sorting multiple columns simultaneously in ascending order

is it possible to sorting multiple columns simultaneously in ascending order in R or Excel? In excel i can't make it all the time. in R, I know we may need order(). Could you give me some advice about it? it's ok to take dataframe n4 as an example. Maybe it is a little boring,i just want to have a cursory look at the number distribution difference. Thank you very much.

n1<-c(7.3,12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,2.5)
n2<-c(5.2,6.0,5.5,2.0,NA,6.7,5.6,3.5,10.4,6.8)
n3<-c(5.6,5.8,13.3,13.8,3.0,10.1,10.7,7.7,12.3,15.8)
n4<-data.frame(n1,n2,n3)

Created on 2022-10-31 with reprex v2.0.2

Hey,

this is not what you should do in R and hence you could work around (like extract and sort each column by its own and then bind them back together). But why you should not do this, is because a data.frame has to be thought of a collection of observations. Each column should be a different feature and every row a distinct observation of all features. If you order multiple columns (in whatever order), you would break the observations apart and would produce a totally different dataset.

However, if you want to ignore this advice, you could use something like this:

split_and_order <- function(df, desc = FALSE, na.last = TRUE){
  # initialize a result list
  result <- vector(mode = 'list', length = ncol(df))
  # sort each column individually
  for(i in seq.default(1,ncol(df))){
    result[[i]] <- df[,i] |> sort(decreasing = desc, na.last = na.last)
  }
  # combine them back to a data.frame
  result <- as.data.frame(result)
  # get back original names
  colnames(result) <- colnames(df)

  result
}
split_and_order(n4, desc = FALSE, na.last = TRUE)
#>      n1   n2   n3
#> 1   2.5  2.0  3.0
#> 2   7.3  3.5  5.6
#> 3   7.6  5.2  5.8
#> 4   9.5  5.5  7.7
#> 5  10.2  5.6 10.1
#> 6  11.8  6.0 10.7
#> 7  12.5  6.7 12.3
#> 8  13.7  6.8 13.3
#> 9  15.0 10.4 13.8
#> 10 18.4   NA 15.8

Created on 2022-10-31 with reprex v2.0.2

Kind regards

1 Like

Thank you very much. I agree with what you said. You made the logic behind it clear to me, i accept your advice.

Please consider axcepting the answer if it solved your problem. :slight_smile:

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.