[英]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.