I have a data frame with a number of fixed columns,
followed by a variable number of columns, depending on the input.
dd <- data.frame(key1=c("NED", "LTU", "LAT", "ITA"), h=c(18, 3, 2, 59)) # Two columns.
dd <- rbind(dd, dd, dd) # example dataframe.
# Append a random number of auxiliary columns, ak1, ak2, ...
set.seed(2024); n <- sample(4:8, size=1) # number of aux. columns.
akeys <- matrix(sample(x=c(1,2,3), size=nrow(dd) * n, replace=TRUE),
ncol=n
) # with random values 1..3.
colnames(akeys) <- paste0("ak", seq(n)) # column names: ak1, ak2, ...
d2 <- cbind(dd, akeys) # append n columns for sorting.
# Assuming n = 5.
d3 <- d2[order(d2$key1, d2$h, d2$ak1, d2$ak2, d2$ak3, d2$ak4, d2$ak5),] # Sort all columns by name.
d4 <- d2[order(d2[,1], d2[,2], d2[,3], d2[,4], d2[,5], d2[,6], d2[, 7]), ] # Sort by column number.
Q: How to sort the data frame by (a selection of) all columns without knowing the columns beforehand.
For example:
- sort the data frame by all columns.
- sort the data frame by key1, and the last n columns.