r - 通向地图的管道最终给出了不正确长度的列表
问题描述
使用该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
解决方案
事情就是这样,当我把你的矩阵变成一个小标题,然后一个列表我得到你想要的输出。由于每个数据框/小标题也是一个列表,因此每一列都相当于列表的一个元素。
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"
推荐阅读
- python - 如何交换一个数组中的两个元素?
- c# - 在 VSTO 插件中获取 Word 进程的键盘输入
- android - 如何为此 JSON 响应生成 POJO 文件以进行自动反序列化?
- reactjs - How to How to fix "No 'Access-Control-Allow-Origin' header is present on the requested resource" in post call in reactJS using Fetch method
- asp.net-mvc - 更新时扩展 Azure Map 标记
- c# - 如何从具有不同角色的用户中插入不同的 user_id
- node.js - 尝试发布到 Web API 时如何修复错误“交通控制违规”
- python - 是否有可能将输出的长向量切割成特定的部分并将它们保存在 excel 的不同单元格中?
- c# - Azure Cosmos db 引发套接字异常
- java - 如何在spring-batch步骤中使用不同的线程进行读取、处理和写入?