简体   繁体   English

如何在R中比较两个相同长度的向量,但不是逐个对象地比较

[英]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. 我需要比较两个形状矢量:如果A的对象等于B的对象的第一个元素,则用B的对象替换A的对象。
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] . 对于上述示例,对象A[1]a ,将与B[2]a xxx匹配,因此对象A [1]将被对象B[2]代替。 Finally A would be with the following elements: "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx" 最后, A将具有以下元素: "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx"

You can use %in% and match like this: 您可以使用%in%进行match如下所示:

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. 在这里, %in%选择要替换的A的位置,然后match找到正确的替换顺序。 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. 使用nomatch=FALSE以便忽略A中不在B中的元素,而不是返回NA,这是默认值。 substr is used to pull out the first character of B for matching. substr用于提取B的第一个字符进行匹配。

logic : we iterate through each of A and then using grepl we get the indices from B . 逻辑:我们遍历每个A ,然后使用greplB获得索引。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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