【发布时间】:2014-10-31 01:12:39
【问题描述】:
标题并没有真正解决这个问题,但我想不出任何其他方式来表达这个问题。我可以用一个例子来最好地解释这个问题。
假设我们有两个数字向量(每个向量总是升序且唯一):
vector1 <- c(1,3,10,11,24,26,30,31)
vector2 <- c(5,9,15,19,21,23,28,35)
我要做的是创建一个函数,该函数将采用这两个向量并按以下方式匹配它们:
1) 从vector1的第一个元素开始(在本例中为1)
2) 转到vector2并将#1中的元素与vector 2中大于它的第一个元素(在本例中为5)匹配
3) 回到vector1并跳过所有小于我们找到的#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)
}
【问题讨论】: