Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting dataframe to achieve desired form

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

like image 295
RuddThreeTrees Avatar asked Sep 16 '25 16:09

RuddThreeTrees


2 Answers

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
like image 105
Maël Avatar answered Sep 18 '25 08:09

Maël


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
like image 34
Quinten Avatar answered Sep 18 '25 09:09

Quinten