Haakonkas Haakonkas - 1 year ago 169
R Question

How to simply extract many repetitive rows from dataframe

How do I easily generate this sequence?

c(1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9,1,10,
2,3,2,4,2,5,2,6,2,7,2,8,2,9,2,10)


Is there any simple way to write this?

Answer Source

Here's a partially-dplyr solution. (Of course it would be trivial to use a replacement for filter() and not use the pipes...) expand.grid normally works well for this, but in this case it's a little more complicated than CPak's use of combn because we have to switch the column order:

expand.grid(1:10, 1:10) %>% rev %>% filter(Var2 < Var1) %>% t %>% as.vector
 [1]  1  2  1  3  1  4  1  5  1  6  1  7  1  8  1  9  1 10  2  3  2  4  2  5  2  6  2
[28]  7  2  8  2  9  2 10  3  4  3  5  3  6  3  7  3  8  3  9  3 10  4  5  4  6  4  7
[55]  4  8  4  9  4 10  5  6  5  7  5  8  5  9  5 10  6  7  6  8  6  9  6 10  7  8  7
[82]  9  7 10  8  9  8 10  9 10

Adding a base method:

n = 10
unlist(lapply(1:(n - 1), FUN = function(x) as.vector(rbind(x, (x + 1):n))))

For large n, I would expect this to be quite a bit faster as it doesn't use data frames at all and doesn't generate unneeded combinations and then filter them out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download