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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With