简体   繁体   中英

How to compare two vectors of the same length in R, but not object by object

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"

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.

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" 

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM