我想按字符串索引
对矩阵进行排序例如
矩阵是我的myMat =
[1] [2]
[1,]苹果1
[2,1]香蕉3
[3,]梨4
[4,]黑莓5
索引字符串为
myIdx =
[1,]香蕉
[2,1]梨
[3,]苹果
[4,]黑莓
结果必须是
myResult =
[1] [2]
[1,]香蕉3
[2,1]梨4
[3,]苹果1
[4,]黑莓5
我怎么这样排序?感谢
答案 0 :(得分:1)
使用data.table
套餐,您可以轻松完成
myMat <- data.frame(fruit = c("apple", "banana", "pear", "blackberry"), num = c(1, 3, 4, 5))
myIdx <- c("banana", "pear", "apple", "blackberry")
require(data.table)
myMat <- data.table(myMat)
myMat
## fruit num
## 1: apple 1
## 2: banana 3
## 3: pear 4
## 4: blackberry 5
setkey(myMat, fruit)
myMat[J(myIdx)]
## fruit num
## 1: banana 3
## 2: pear 4
## 3: apple 1
## 4: blackberry 5