Arrays 合并数组'x'和'y',对应于'x'的相等元素` 让我们考虑两个长度相同的数组,例如,下面的 x<-c(1,1,2,2,3,4,5,6,7,8) y<-c(1,2,3,4,4,4,5,6,6,6)

Arrays 合并数组'x'和'y',对应于'x'的相等元素` 让我们考虑两个长度相同的数组,例如,下面的 x<-c(1,1,2,2,3,4,5,6,7,8) y<-c(1,2,3,4,4,4,5,6,6,6),arrays,r,Arrays,R,我可以通过for循环和if-else语句执行此操作,但我想知道是否有更有效的解决方案。它仍然是一个循环,但使用sapply sapply(seq_along(x), function(i) { #Compare values from ith index to end of the array with x[i] inds = x[min(i+1, length(x)):length(x)] == x[i] #If there are any similar values

我可以通过for循环和if-else语句执行此操作,但我想知道是否有更有效的解决方案。

它仍然是一个循环,但使用
sapply

sapply(seq_along(x), function(i) {
    #Compare values from ith index to end of the array with x[i]
    inds = x[min(i+1, length(x)):length(x)] == x[i]
    #If there are any similar values return the max y value
    if(any(inds))  max(y[i:(which.max(!inds) - 1 + i)])
    #return the corresponding y value
    else   y[i]
})

#[1] 2 2 4 4 4 4 5 6 6 6

对于
i==2
没有
x[i+k]==x[i]
因此
z[j]==y[i]
哪个是2而不是4?
sapply(seq_along(x), function(i) {
    #Compare values from ith index to end of the array with x[i]
    inds = x[min(i+1, length(x)):length(x)] == x[i]
    #If there are any similar values return the max y value
    if(any(inds))  max(y[i:(which.max(!inds) - 1 + i)])
    #return the corresponding y value
    else   y[i]
})

#[1] 2 2 4 4 4 4 5 6 6 6