Reputation: 29
Example: I have two vector with the following structure (also they can be two columns of a data frame).
A <- c("a", "d", "f", "a", "n", "d", "d")
B <- c("h xx", "a xxx", "f xxxx", "d xxxxx", "a xxx", "h xx", "f xxxx")
I need compare the two vectors of shape that if an object of A if equal to first element of an object of B,
replace that object of A with the object of B.
For the example presented above, the object A[1]
that is a
, will match with the B[2]
that is a xxx
, so object A [1]
, will be replaced for object B[2]
.
Finally A
would be with the following elements: "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx"
Upvotes: 1
Views: 932
Reputation: 38500
You can use %in%
and match
like this:
A[A %in% substr(B, 1, 1)] <- B[match(A, substr(B, 1, 1), nomatch=FALSE)]
A
[1] "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx"
Here, %in%
selects the positions of A to replace, and match
finds the proper order of replacement. The nomatch=FALSE
is used so that elements in A that are not in B are ignored rather than returning NA, which is the default. substr
is used to pull out the first character of B for matching.
Upvotes: 3
Reputation: 8413
logic : we iterate through each of A
and then using grepl
we get the indices from B
.
sapply(A, function(x) {if(any(grepl(x, B))) x <- B[grepl(x, B)][1];x})
# a d f a n d d
# "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx"
Upvotes: 1
Reputation: 309
Hi is this what you are looking for:
for(i in 1:length(A)){
for(j in 1:length(B)){
if(A[i] == substr(B[j], 1, 1)){
A[i] <- B[j]
}
}
}
# [1] "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx"
Upvotes: 1