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

Trying to find a better way to sorting the data in R

In my data frame I am trying to sort the data in descending order. I am using the below line of code for sorting my data and it works as intended.

CNS25VOL <- CNS25VOL[order(-CNS25VOL$MATVOL22), ]

However if I refer to the same column by it’s index number, the code throws an error

CNS25VOL <- CNS25VOL[order(-CNS25VOL[, 2]), ]

Error thrown is

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

Error in CNS25VOL[, 2] : incorrect number of dimensions

While I do have a solution to what I am intending to do, but issue I see is if all of a sudden name of my column changes the code won’t work. I know that their position will stay same in the data frame.

How can we handle it.

>Solution :

order(-CNS25VOL[, 2]) order here does expect a vector which you try to construct via the [] in CNS25VOL[, 2]. Normal dataframes will return a vector consisting only of the 2nd column. A tibble however will return a tibble with only one column.

You can reproduce the behaviour of normal data.frames with the drop = FALSE argument to [] as in

CNS25VOL[, 2, drop = TRUE]

Try to always be aware whether you are using a standard data.frame or a tibble or a data.table because they look very similar and are not in the details. Also see https://tibble.tidyverse.org/reference/subsetting.html

dplyr functions tend to give you a tibble back even if you fed them a classical data.frame.

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