1
標題並沒有真正做到這個問題正義,但我想不出任何其他方式來描述問題。我可以用一個例子來最好地解釋這個問題。在兩個不同的向量中按照它們的順序匹配數字
比方說,我們有一個數字的兩個向量(其中的每一個總是會被上升的和獨特的):
vector1 <- c(1,3,10,11,24,26,30,31)
vector2 <- c(5,9,15,19,21,23,28,35)
我所試圖做的是創造條件,採取這兩個向量函數,以下面的方式與它們匹配:
1)開始與向量1的第一個元素(在此情況下,1)
2)轉到vector2和在載體2從#1的元件與所述第一元件相匹配比它大(在這種情況下,5)
3)返回向量1,並跳過小於在#2中,我們找到的值(在這種情況下,我們跳過3的所有元素,並抓住10)
4)回到vector2並跳過所有元素小於我們找到的#3中的值(在這種情況下,我們跳過9並搶15)
5)重複,直到我們完成所有元素。
我們應該得到的兩個向量:
result1 = c(1,10,24,30)
result2 = c(5,15,28,35)
我目前的解決方案是這樣的,但我認爲這可能是非常低效的:
# establishes where we start from the vector2 numbers
# just in case we have vector1 <- c(5,8,10)
# and vector2 <- c(1,2,3,4,6,7). We would want to skip the 1,2,3,4 values
i <- 1
while(vector2[i]<vector1[1]){
i <- i+1
}
# starts the result1 vector with the first value from the vector1
result1 <- vector1[1]
# starts the result2 vector empty and will add as we loop through
result2 <- c()
# super complicated and probably hugely inefficient loop within a loop within a loop
# i really want to avoid doing this, but I cannot think of any other way to accomplish this
for(j in 1:length(vector1)){
while(vector1[j] > vector2[i] && (i+1) <= length(vector2)){
result1 <- c(result1,vector1[j])
result2 <- c(result2,vector2[i])
while(vector1[j] > vector2[i+1] && (i+2) <= length(vector2)){
i <- i+1
}
i <- i+1
}
}
## have to add on the last vector2 value cause while loop skips it
## if it doesn't exist (there are no more vector2 values bigger) we put in an NA
if(result1[length(result1)] < vector2[i]){
result2 <- c(result2,vector2[i])
}
else{
### we ran out of vector2 values that are bigger
result2 <- c(result2,NA)
}
即這樣一個聰明的解決方案。我從來沒有想過交錯兩個向量(我想我沒有充分利用我的上升和唯一性假設)。 我只是改變了最後一行代碼,並得到它的工作。非常感謝! – 2014-10-31 22:10:21
對不起,麻煩了,但是當我試圖將它與我以前的解決方案進行比較時,我發現了一個錯誤。如果vector1的值從vector2的值開始,則輸出不正確。例如,vector1 =(3,10,...)和vector2是(1,5,9 ...) 我通過簡單地調整vector2來刪除低於vector1的初始值的任何值,可以解決此問題。 – 2014-10-31 22:41:44
can你只是使用vector2作爲矢量1,反之亦然?也就是說,總是先使用具有最小第一個元素的向量? – rawr 2014-10-31 23:53:28