簡體   English   中英

如何在R中比較兩個相同長度的向量,但不是逐個對象地比較

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

示例:我有兩個具有以下結構的向量(它們也可以是數據幀的兩列)。

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")

我需要比較兩個形狀矢量:如果A的對象等於B的對象的第一個元素,則用B的對象替換A的對象。
對於上述示例,對象A[1]a ,將與B[2]a xxx匹配,因此對象A [1]將被對象B[2]代替。 最后, A將具有以下元素: "a xxx" "d xxxxx" "f xxxx" "a xxx" "n" "d xxxxx" "d xxxxx"

您可以使用%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"

在這里, %in%選擇要替換的A的位置,然后match找到正確的替換順序。 使用nomatch=FALSE以便忽略A中不在B中的元素,而不是返回NA,這是默認值。 substr用於提取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" 

您好,這是您要找的東西:

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