How to cross-paste all combinations of two vectors (each-to-each)?

后端 未结 4 1418
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 06:04

I need to paste all combinations of elements from two character vectors, \"each\" to \"each\": instead of

> paste0(c(\"a\", \"b\"), c(\"c\", \"d\"))
[1]          


        
4条回答
  •  一个人的身影
    2020-12-09 06:26

    You can also do:

    outer(c("a", "b"), c("c", "d"), FUN = "paste0")[1:4]
    [1] "ac" "bc" "ad" "bd"
    

    Both do.call and outer are valuable functions to play with. :)

    Alternately, we can assign

    x <- outer(c("a", "b"), c("c", "d"), FUN = "paste0")
    dim(x) <- NULL
    x
    [1] "ac" "bc" "ad" "bd"
    

    Without knowing the length.

    More edits!

    x <- outer(c("a", "b"), c("c", "d"), FUN = "paste0")
    y <- t(x)
    dim(y) <- NULL
    y
    [1] "ac" "ad" "bc" "bd"
    

    Gets you the desired order, too.

提交回复
热议问题