R語言 -- 交并補(bǔ):intersect计福、union跌捆、setdiff、Reduce多重操作
> # 交并補(bǔ)
> a = seq(0, 40, 4); a
[1] 0 4 8 12 16 20 24 28 32 36 40
> b = seq(0, 40, 5); b
[1] 0 5 10 15 20 25 30 35 40
>
> # 交集
> intersect(a,b)
[1] 0 20 40
>
> # 并集
> union(a,b)
[1] 0 4 8 12 16 20 24 28 32 36 40 5 10 15 25 30 35
>
> # a 減去 a交b
> setdiff(a,b)
[1] 4 8 12 16 24 28 32 36
>
> # b 減去 a交b
> setdiff(b,a)
[1] 5 10 15 25 30 35
>
> # 多個集合之間操作
> Reduce(union, list(v1 = c("a","b","c","d"),
+ v2 = c("a","b","e"),
+ v3 = c("a","f","g"),
+ v4 = c("a","f","e","g"))
+ )
[1] "a" "b" "c" "d" "e" "f" "g"
>
> Reduce(intersect, list(v1 = c("a","b","c","d"),
+ v2 = c("a","b","e"),
+ v3 = c("a","f","g"),
+ v4 = c("a","f","e","g"))
+ )
[1] "a"
>
> Reduce(setdiff, list(v1 = c("a","b","c","d"),
+ v2 = c("a","b","e"),
+ v3 = c("a","f","g"),
+ v4 = c("a","f","e","g"))
+ )
[1] "c" "d"