I have this for loop which return the first matching index of every element in the vector but it is very slow (nrow(data) > 50 000)
example:
id1 <- c(1,5,8,10)
id2 <- c(5,8,10,1)
data <- data.frame(id1,id2, idx = 1:length(id1))
results should be :
data$new_id
4 1 2 3
data$new_id <- NA
for(i in 1:nrow(data)){
data$new_id[i] <- which(data$id2 == data$id1[i])
}
I found that this works for small data frame but unfortunatly R return a "Error: cannot allocate vector of size 22.2 Gb"
A <- outer(data$id1,data$id2, "==")
data <- data %>%
mutate(new_id = which(t(A)),
id0 = 0:(nrow(data)-1),
new_id = new_id-(nrow(data))*id0)
Does other solution exist to do this indexing ?