Search code examples
rstringvectorcombinationspermutation

Is there a function to concatenate all the elements in a vector?


I have made a vector which looks like this:

v1 <- c("1 1","1 2","1 3",
        "2 1","2 2","2 3",
        "3 1","3 2","3 3",
        "4 1","4 2","4 3",
        "5 1","5 2","5 3",
        "6 1","6 2","6 3")

It can be called v1.

The result I want is "1 1 1 1" "1 1 1 2" .... "6 6 6 6" (in total should be 6x3x6x3=360-36=324 in total into a new vector v2)

However, I have tried apply(combn(v1, 2), 2, paste0, collapse=" ") but it is not complete.

How can I achieve the goal?


Solution

  • Get all combinations, then paste:

    v2 <- do.call(paste, expand.grid(v1, v1))
    

    Check the output:

    head(v2)
    # [1] "1 1 1 1" "1 2 1 1" "1 3 1 1" "2 1 1 1" "2 2 1 1" "2 3 1 1"
    tail(v2)
    # [1] "5 1 6 3" "5 2 6 3" "5 3 6 3" "6 1 6 3" "6 2 6 3" "6 3 6 3"    
    length(v2)
    # [1] 324