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:
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?
CodePudding user response:
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),]