如何比较R中相同长度的两个向量,而不是逐个对象
示例:我有两个具有以下结构的向量(它们也可以是数据帧的两列)如何比较R中相同长度的两个向量,而不是逐个对象,r,R,示例:我有两个具有以下结构的向量(它们也可以是数据帧的两列) A逻辑:我们迭代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
A逻辑:我们迭代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"
sapply(A,函数(x){if(any)(grepl(x,B)))x逻辑:我们迭代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"
sapply(A,函数(x){if(any)(grepl(x,B)))xHi这就是你要找的:
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"
for(1中的i:长度(A)){
对于(j/1:长度(B)){
如果(A[i]==substr(B[j],1,1)){
A[i]嗨,这就是你要找的东西:
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"
for(1中的i:长度(A)){
对于(j/1:长度(B)){
如果(A[i]==substr(B[j],1,1)){
A[i]您可以使用%
中的%和匹配
如下:
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"
A[A%in%substr(B,1,1)]您可以像这样使用%in%
和匹配
:
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"
A[A%in%substr(B,1,1)]像往常一样你总是给出简洁的!!+1!像往常一样你总是给出简洁的!!+1!