假設我有矢量vec <- c("D","B","B","C","C")
。用於查找與矢量中唯一值關聯的索引的高效R代碼
我的目標是與尺寸length(unique(vec))
,其中該列表中的每個i
返回一個表示在vec
的unique(vec)[i]
位置索引的向量的列表結束。
例如,這個列表vec
將返回:
exampleList <- list()
exampleList[[1]] <- c(1) #Since "D" is the first element
exampleList[[2]] <- c(2,3) #Since "B" is the 2nd/3rd element.
exampleList[[3]] <- c(4,5) #Since "C" is the 4th/5th element.
我嘗試以下方法,但它的速度太慢。我的例子是大的,所以我需要更快的代碼:
vec <- c("D","B","B","C","C")
uniques <- unique(vec)
exampleList <- lapply(1:3,function(i) {
which(vec==uniques[i])
})
exampleList
@阿倫好點,謝謝!有些令我驚訝的是它並沒有影響計時 - 我猜這只是太便宜而無法複製 – eddi
有趣...我用你的data.table代碼得到了不同的結果:在我的電腦中dt變成> dt vec V1 1:D 4,5 2:B 4,5 3:C 4,5( - 也就是說,V1的所有元素均相等於4:5)。 – lebatsnok
@lebatsnok你正在運行什麼版本的'data.table'? (我使用1.9.3) – eddi