我有两个向量,即d1
和d2
。
d1 <- c("Dog", "Cat", "Lion", "Tiger", "Horse")
d2 <- c("Tiger", "Rat", "Lion", "Horse","Dog")
我想检查d1
的第一个位置中的矢量是否与d2
的第五个位置匹配。类似地检查向量d1
中的第二位置是否与向量d2
的第四位置匹配,依此类推。有三种可能的结果:-
a(d1
中的矢量存在于矢量d2
中,并且位置也匹配。
b(d1
中的矢量存在于矢量d2
中。但这些位置并不匹配。
c(d1
中的矢量不包含在d2
中。
预期输出如下:-
Dog is present in the second vector and the positions match.
Cat is not present in the second vector.
Lion is present in the second vector and the positions match.
Tiger is present in the second vector. But the positions do not match.
Horse is present in the second vector. But the positions do not match.
您可以使用函数和数据帧并使用@Roland:的有用注释来尝试这种方法
d1 <- c("Dog", "Cat", "Lion", "Tiger", "Horse")
d2 <- c("Tiger", "Rat", "Lion", "Horse","Dog")
check_function <- function(x,y)
{
df <- data.frame(v1=x,v2=rev(y),stringsAsFactors = F)
df$i1 <- df$v1 %in% df$v2
df$i2 <- df$v1==df$v2
#Create messages
df$Message <- ifelse(df$i1==T & df$i2==T,paste0(df$v1,' is present in second vector and match'),
ifelse(df$i1==T & df$i2==F,paste0(df$v1,' is present in second vector but no match'),
paste0(df$v1,' is not present in second vector')))
return(df$Message)
}
check_function(d1,d2)
[1] "Dog is present in second vector and match" "Cat is not present in second vector"
[3] "Lion is present in second vector and match" "Tiger is present in second vector but no match"
[5] "Horse is present in second vector but no match"