Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match vectors in sequence

I have 2 vectors.

x=c("a", "b", "c", "d", "a", "b", "c")
y=structure(c(1, 2, 3, 4, 5, 6, 7, 8), .Names = c("a", "e", "b", 
"c", "d", "a", "b", "c"))

I would like to match a to a, b to b in sequence accordingly, so that x[2] matches y[3] rather than y[7]; and x[5] matches y[6] rather than y[1], so on and so forth.

lapply(x, function(z) grep(z, names(y), fixed=T))

gives:

[[1]]
[1] 1 6

[[2]]
[1] 3 7

[[3]]
[1] 4 8

[[4]]
[1] 5

[[5]]
[1] 1 6

[[6]]
[1] 3 7

[[7]]
[1] 4 8

which matches all instances. How do I get this sequence:

1 3 4 5 6 7 8

So that elements in x can be mapped to the corresponding values in y accordingly?

like image 695
Sati Avatar asked May 02 '18 07:05

Sati


4 Answers

You are actually looking for pmatch

pmatch(x,names(y))
[1] 1 3 4 5 6 7 8
like image 55
KU99 Avatar answered Nov 10 '22 04:11

KU99


You can change the names attributes according to the number of times each element appeared and then subset y:

x2 <- paste0(x, ave(x, x, FUN=seq_along))
#[1] "a1" "b1" "c1" "d1" "a2" "b2" "c2"
names(y) <- paste0(names(y), ave(names(y), names(y), FUN=seq_along))
y[x2]
#a1 b1 c1 d1 a2 b2 c2 
# 1  3  4  5  6  7  8 
like image 45
talat Avatar answered Nov 10 '22 02:11

talat


Another option using Reduce

Reduce(function(v, k) y[-seq_len(v)][k],
    x=x[-1L],
    init=y[x[1L]], 
    accumulate=TRUE)
like image 3
chinsoon12 Avatar answered Nov 10 '22 02:11

chinsoon12


Well, I did it with a for-loop

#Initialise the vector with length same as x.
answer <- numeric(length(x))
for (i in seq_along(x)) {
  #match the ith element of x with that of names in y.
  answer[i] <- match(x[i], names(y))
  #Replace the name of the matched element to empty string so next time you 
  #encounter it you get the next index.
  names(y)[i] <- ""
}

answer
#[1] 1 3 4 5 6 7 8
like image 2
Ronak Shah Avatar answered Nov 10 '22 03:11

Ronak Shah