Reputation: 121
sampleFiles <- list.files(path="/path",pattern="*.txt");
> sampleFiles
[1] "D104.txt" "D121.txt" "D153.txt" "D155.txt" "D161.txt" "D162.txt" "D167.txt"
[8] "D173.txt" "D176.txt" "D177.txt" "D179.txt" "D204.txt" "D221.txt" "D253.txt"
[15] "D255.txt" "D261.txt" "D262.txt" "D267.txt" "D273.txt" "D276.txt" "D277.txt"
[22] "D279.txt" "N101.txt" "N108.txt" "N113.txt" "N170.txt" "N171.txt" "N172.txt"
[29] "N175.txt" "N181.txt" "N182.txt" "N183.txt" "N186.txt" "N187.txt" "N188.txt"
[36] "N201.txt" "N208.txt" "N213.txt" "N270.txt" "N271.txt" "N272.txt" "N275.txt"
[43] "N281.txt" "N282.txt" "N283.txt" "N286.txt" "N287.txt" "N288.txt"
How can I get all started with "N" first and "D" last? In other words swap them.
Upvotes: 0
Views: 65
Reputation: 263411
In this case it would be as simple as:
sampleFiles[c(23:48, 1:22)]
More general solutions have been suggested including, but sort(sampleFiles)
would NOT succeed with "D" < "N". You could have used:
sampleFiles[rev(order(substr(sampleFiles, 1,1)))]
If you just used:
sampleFiles[rev(order(sampleFiles, 1,1))]
.. then the numeric values would get reversed as well. So you could have used chartr
to swap them as the argument to order
to selectively reverse the values of only "D" and "N":
sampleFiles[ order( chartr(c("DN"), c("ND"), sampleFiles) ) ]
Upvotes: 1
Reputation: 13122
If you want to sort by letter (N, D) and number (101, ..) you could -just- swap your elements:
#random vector
vec <- c("D104.txt", "D121.txt", "D279.txt", "N101.txt", "N108.txt", "N113.txt")
#swap places
vec[c(grep("N", vec), grep("D", vec))]
[1] "N101.txt" "N108.txt" "N113.txt" "D104.txt" "D121.txt" "D279.txt"
grep
finds what element of the vector has the pattern wanted. So, we move elements with "N" in front and with "D" in the back.
If you just want to sort with letters and numbers decreasing, you just (like Thomas suggested):
sort(vec, decreasing = T)
[1] "N113.txt" "N108.txt" "N101.txt" "D279.txt" "D121.txt" "D104.txt"
Also, since you know the indices of the elements you want to swap, then:
sampleFiles[c(23:48, 1:22)]
Upvotes: 1