使用combn
函数,当选择2个元素(m = 2
(时,我想生成向量c("1", "2", "3")
的所有可能组合。代码如下:
comparisons <- combn(c("1", "2", "3"), m = 2)
[,1] [,2] [,3]
[1,] "1" "1" "2"
[2,] "2" "3" "3"
然后我转换这个数据帧,所以它变成这样:
comparisons <- t(comparisons)
[,1] [,2]
[1,] "1" "2"
[2,] "1" "3"
[3,] "2" "3"
最后一步是生成一个列表,其中每个元素都是这个转置数据帧中的一行。我用了地图,它给了我想要的东西:
comparisons <- map(1:3, ~ comparisons[.x, ])
[[1]]
[1] "1" "2"
[[2]]
[1] "1" "3"
[[3]]
[1] "2" "3"
这一切都很好,但当我试图在一个漂亮的作业中将所有这些管道连接在一起时,结果列表是不正确的。
comparisons <- combn(c("1", "2", "3"), m = 2) %>%
t() %>%
map(1:3, ~ .[.x, ])
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
[[6]]
NULL
事情是这样的,当我把你的矩阵变成tibble,然后把列表变成你想要的输出。由于每个数据帧/tibble也是一个列表,因此每一列都相当于列表的一个元素。
package(purrr)
comparisons %>%
as_tibble() %>%
as.list() %>% # Up here it will get your desire output but if you want to transpose it however you can run the last line of code.
transpose()
$a # Before running transpose
[1] "1" "2"
$b
[1] "1" "3"
$c
[1] "2" "3"
# After running tranpose
[[1]]
[[1]]$a
[1] "1"
[[1]]$b
[1] "1"
[[1]]$c
[1] "2"
[[2]]
[[2]]$a
[1] "2"
[[2]]$b
[1] "3"
[[2]]$c
[1] "3"