I am stuck in a complicated problem in R and cannot solve it. The problem is this.
x and y are two vectors as follows:
x<- c(1,2,3,4,5)
y<- c(12,4,2,5,7,18,9,10)
I want to create a new vector p, where length (p) = length (x), as follows:
- For each id in x, find the id in y that has the minimum absolute distance in terms of values. For example, for id = 1 in x, value_x (id = 1) = 1, min_value_y = 2, and id_y (value == 2) = 3. Thus, the answer to id 1 in x is 3. Thus, we create a new vector p, which will have the following meanings: p = (3,3,3,2,4);
Now we must update p as follows:
- Since 3 was an id corresponding to id_x = 1, it cannot be id_x = 2. Therefore, we must discard id_y = 3 with a value of 2 in order to calculate the next minimum distance for id_x = 2. The next best minimum distance for id_x = 2 is id_y = 2 with a value of 4. Therefore, the updated p is (3,2,3,2,4).
- Since 3 was an id corresponding to id_x = 1, it cannot be id for id_x = 3. Therefore, we must discard id_y = 3 with a value of 2 in order to calculate the next minimum distance for id_x = 3. The next best minimum distance for id_x = 3 is equal to 2. Therefore, the updated p is equal to (3,2,4,2,4).
p 2 4, , . , x y id x id of y, . , p .
.
- , :
minID <- function(x,y) {return(which(abs(x-y)==min(abs(x-y))))};
p1 <- sapply(x,minID,y=y);
x y 1 , . .