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.
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