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

Reordering an integer column in a data frame gives incorrect order

I am retrieving a list of files in my folder and I want to create a data frame. The files in the folder all contain the names "1.png", "2.png", etc. I want to create a data frame with a column named "Number" and a column named "Extension" and reorder the data frame based on the numerical values of the "Number" column.

I start by extracting the list of files into a data frame:

MyList <- data.frame(Number = list.files(path), Extension = NA)

Which ends up looking like this:

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

   Number Extension
1   1.png        NA
2  10.png        NA
3  11.png        NA
4  12.png        NA
5  13.png        NA

And so on… Next I split the Numbers based on the dots:

MyList$Extension <- lapply(strsplit(MyList$Number, "\\."), "[", 2)
MyList$Number <- lapply(strsplit(MyList$Number, "\\."), "[", 1)

Which gives me:

 Number Extension
1     1       png
2    10       png
3    11       png
4    12       png
5    13       png

So far so good… Now all I need is to reorder the data frame in ascending order based on the column "Number":

MyList$Number <- order(as.numeric(MyList$Number), decreasing = FALSE)

And the result:

 Number Extension
1     1       png
2    22       png
3    33       png
4    34       png
5    35       png

For some reason that didn’t work? I expected it to be ordered like this:

 Number Extension
1     1       png
2     2       png
3     3       png
4     4       png
5     5       png

etc… The column "Number" is of class integer:

> class(MyList$Number)
[1] "integer"

What went wrong?

>Solution :

If we need the actual values ordered, use the index from the order the dataset using the index as row index instead of assigning the index as the column ‘Number’

MyList <- MyList[order(as.numeric(MyList$Number), decreasing = FALSE),]
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