Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate running combinations of vector values in R

Tags:

r

dplyr

tidyr

What I need to achieve is basically a list of all combinations of vector values but running trough windows of a given length. It's more easier to show than to explain.

Let say I have a window.size of 3

vector <- c("goofy", "mickey", "donald", "foo", "bar")

This is what I need as output

from  |  to
------+-----
goofy | mickey
goofy | donald
mickey| donald
mickey| foo
donald| bar
donald| foo
foo   | bar

As this is going to end in a monte carlo set of iterations, windows.size should be parametric

I think it could be easily done with dplyr and tidyr but I was not able to figure out how.

Thanks in advance!

like image 982
Gabriele B Avatar asked Jan 23 '26 20:01

Gabriele B


1 Answers

With rollapply and dplyr. The c, do.call, as.data.frame ugliness are needed to convert the output of combn to a dataframe for dplyr functions:

library(zoo)
library(dplyr)

rollapply(vector, 3, combn, 2, simplify = FALSE) %>%
  c() %>%
  do.call(rbind, .) %>%
  as.data.frame() %>%
  distinct() %>%
  setNames(c("from", "to"))

Result:

    from     to
1  goofy mickey
2 mickey donald
3 donald    foo
4  goofy donald
5 mickey    foo
6 donald    bar
7    foo    bar
like image 99
acylam Avatar answered Jan 26 '26 10:01

acylam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!