user124123
user124123

Reputation: 1683

Pass three commands to intersect in R

I am using the intersect function, and was wondering if there is any way to pass three commands rather than just two: i.e

colnames(df[ intersect ( grep("name",colnames(df) ), grep("name",colnames(df) ), grep("name",colnames(df),invert=TRUE)   )])

This is giving me an error:

Error in base::intersect(x, y, ...) 

Upvotes: 0

Views: 378

Answers (2)

Roland
Roland

Reputation: 132706

Use Reduce:

x <- letters[1:5]
y <- letters[2:6]
z <- letters[3:7]

Reduce(intersect, list(x, y, z))
#[1] "c" "d" "e"

Upvotes: 5

user124123
user124123

Reputation: 1683

Have realised intersect is associative so you can put one inside of another:

colnames(df[ intersect (intersect ( grep("name",colnames(df) ), grep("name",colnames(df))), grep("name",colnames(df),invert=TRUE)   )])

Upvotes: 0

Related Questions