示例:我有两个具有以下结构的向量(也可以是数据帧的两列)。
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"
将包含以下元素:set @oids :=(
SELECT OBJECT_ID
FROM aaa K
WHERE K.TYPE IN ('ISSN', 'ISBN')
GROUP BY K.OBJECT_ID
HAVING count(distinct K.TYPE) = 2
);
select *
from aaa
where OBJECT_ID in (@oids);
答案 0 :(得分:3)
您可以像这样使用%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的第一个字符进行匹配。
答案 1 :(得分:1)
逻辑:我们遍历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"
答案 2 :(得分:1)
嗨,这就是你要找的东西:
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"