Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading