Home > Mobile >  Sorting dataframe to achieve desired form
Sorting dataframe to achieve desired form

Time:04-08

Good morning everyone

I have the following example:

data <- data.frame(matrix(0, nrow = 3, ncol = 5))
colnames(data) = paste("art_", 1:5, sep = "")
rownames(data) = paste("use_", 1:3, sep = "")
data["use_1",c("art_1","art_2","art_3")] = 1
data["use_2",c("art_2","art_3")] = 1
data["use_3",c("art_1","art_2","art_3","art_4","art_5")] = 1

#This is how the table looks like:
      art_1 art_2 art_3 art_4 art_5
use_1     1     1     1     0     0
use_2     0     1     1     0     0
use_3     1     1     1     1     1

Now i want to rearrange or sort the rows and columns so that all entries with 1 are grouped in the left upper corner. Here is how it should look like after the rearrangement:

      art_2 art_3 art_1 art_4 art_5
use_3     1     1     1     1     1
use_1     1     1     1     0     0
use_2     1     1     0     0     0

Thank you very much for any kind of hints and help.

Cheers

CodePudding user response:

With apply, sort by row (MARGIN = 1) and then by column (MARGIN = 2):

data[] <- t(apply(data, 1, sort, decreasing = T))
data[] <- apply(data, 2, sort, decreasing = T)

      art_1 art_2 art_3 art_4 art_5
use_1     1     1     1     1     1
use_2     1     1     1     0     0
use_3     1     1     0     0     0

CodePudding user response:

You can use the following code:

data[order(rowSums(data), decreasing=TRUE), order(colSums(data), decreasing=TRUE)]

Output:

      art_2 art_3 art_1 art_4 art_5
use_3     1     1     1     1     1
use_1     1     1     1     0     0
use_2     1     1     0     0     0

CodePudding user response:

Another possible solution:

data[names(sort(apply(data, 2, sum), decreasing = T))]

#>       art_2 art_3 art_1 art_4 art_5
#> use_1     1     1     1     0     0
#> use_2     1     1     0     0     0
#> use_3     1     1     1     1     1
  • Related