Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

r - Subsettings rows containing specific values

I am generating a matrix of all combinations of 5 numbers taken 3 at a time, without replacement, like this:

v <- seq(1,5,1) 
combs <- t(combn(v,3))

Part of the output is as following:

    [,1]  [,2]  [,3]
[,1]    1   2   3
[,2]    1   2   4
[,3]    1   2   5
[,4]    1   3   4
[,5]    1   3   5
.
.
.

Now, I want to filter out all rows containing, for example, numbers 1 and 3, where the remaining element doesn't matter. How can this be done?

Thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is one way using rowSums :

combs[rowSums(combs == 1) > 0 & rowSums(combs == 3) > 0, ]

#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    1    3    4
#[3,]    1    3    5

You can also use apply :

combs[apply(combs, 1, function(x) all(c(1, 3) %in% x)), ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...