用23-48交换1-22行

时间:2013-10-20 21:09:36

标签: r row swap

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”开始?换句话说,交换它们。

2 个答案:

答案 0 :(得分: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”。

如果你只想减少字母和数字的排序,你就像(托马斯建议的那样):

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

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

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

答案 1 :(得分:0)

在这种情况下,它将如下:

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

已经提出了更一般的解决方案,包括但是sort(sampleFiles)不能成功用“D”&lt; “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)  ) ]