R语言中取交集函数intersect
1、测试数值
> dat1 <- 1:8 > dat2 <- 3:10 > intersect(dat1, dat2) ## 直接取两个数值型的交集 [1] 3 4 5 6 7 8
2、数值有重复的情况
> dat1 <- c(2, 3, 2, 4, 5, 3, 6, 3, 4, 8) > dat2 <- c(7, 3, 4, 9, 2, 10, 5) > intersect(dat1, dat2) ## intersect可以直接去重复 [1] 2 3 4 5 > intersect(dat2, dat1) ## 交换两个数据的位置,输出的顺序有差异, 但是结果一致 [1] 3 4 2 5
3、字符串的情况
> dat1 <- c("x", "a", "b", "b", "a", "d","c", "f", "d") > dat2 <- c("c", "b","b", "g", "y", "d", "d", "m") > intersect(dat1, dat2) ## 对字符串同样适用 [1] "b" "d" "c" > intersect(dat2, dat1) [1] "c" "b" "d"
4、数值和字符串之间的比较
> dat1 <- c(3, 5, 1, 2,2, 3, 3, 7, 5, 8, 3) > dat2 <- c("2", "3", "9", "5", "6", "1", "10", "1") > class(dat1) [1] "numeric" > class(dat2) [1] "character" > intersect(dat1, dat2) ## intersect函数可以实现字符串与数字的比较, 而且返回值的属性与两个比较数据的位置有关,输出数据类型为第二个数据的属性 [1] "3" "5" "1" "2" > intersect(dat2, dat1) [1] 2 3 5 1