[英]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
,然后使用grepl
從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"
您好,這是您要找的東西:
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.