首页 > 解决方案 > 通向地图的管道最终给出了不正确长度的列表

问题描述

使用该combn函数,我想c("1", "2", "3")在选择 2 个元素 ( m = 2.) 时生成向量的所有可能组合。代码如下所示:

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

标签: rtidyverse

解决方案


事情就是这样,当我把你的矩阵变成一个小标题,然后一个列表我得到你想要的输出。由于每个数据框/小标题也是一个列表,因此每一列都相当于列表的一个元素。

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"


推荐阅读