0
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"

我怎样才能从“N”开始,“D”最后开始?换句话说,交换它们。

4

2 回答 2

1

在这种情况下,它会很简单:

sampleFiles[c(23:48, 1:22)]

已经提出了更通用的解决方案,包括但sort(sampleFiles)不会成功使用“D”<“N”。你可以使用:

 sampleFiles[rev(order(substr(sampleFiles, 1,1)))]

如果您刚刚使用:

sampleFiles[rev(order(sampleFiles, 1,1))]

..那么数值也会被反转。因此,您可以使用chartr交换它们作为参数来order选择性地反转仅“D”和“N”的值:

sampleFiles[ order( chartr(c("DN"), c("ND"), sampleFiles)  ) ]
于 2013-10-20T21:57:54.767 回答
1

如果你想按字母 (N, D)数字 (101, ..) 排序,你可以 - 只是 - 交换你的元素:

#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查找向量的哪个元素具有所需的模式。因此,我们移动前面带有“N”,后面带有“D”的元素。

如果您只想按字母和数字递减排序,您只需(就像 Thomas 建议的那样):

sort(vec, decreasing = T)
[1] "N113.txt" "N108.txt" "N101.txt" "D279.txt" "D121.txt" "D104.txt"

此外,由于您知道要交换的元素的索引,因此:

sampleFiles[c(23:48, 1:22)]
于 2013-10-20T21:26:28.647 回答