我正在寻找函数,比如函数编程语言中的zip/unzip (例如Haskell,Scala)。
Haskell引用中的示例。Zip:
Input: zip [1,2,3] [9,8,7]
Output: [(1,9),(2,8),(3,7)]解压缩:
Input: unzip [(1,2),(2,3),(3,4)]
Output: ([1,2,3],[2,3,4])在R中,输入应该是这样的。拉链:
l1 <- list(1,2,3)
l2 <- list(9,8,7)
l <- Map(c, l1, l2)用于解拉链:
tuple1 <- list(1,2)
tuple2 <- list(2,3)
tuple3 <- list(3,4)
l <- Map(c, tuple1, tuple2, tuple3)R中是否有实现这些方法的内置解决方案/库?(FP函数通常有很多名称--搜索zip/unzip &R只给出压缩/解压缩文件的结果。)
发布于 2016-11-29 02:11:45
紫红色包装试图提供许多FP原语。purrr的zip版本叫做transpose()。
L1 <- list(as.list(1:3),as.list(9:7))
library(purrr)
(L2 <- transpose(L1))
## List of 3
## $ :List of 2
## ..$ : int 1
## ..$ : int 9
## $ :List of 2
## ..$ : int 2
## ..$ : int 8
## $ :List of 2
## ..$ : int 3
## ..$ : int 7
identical(transpose(L2),L1) ## TRUEtranspose()也适用于您的第二个示例(解压缩)。
发布于 2016-11-29 02:19:43
我不认为这正是你想要的,但是如果它是等长的向量,你可以遵循一个数组,然后用拆分来表示两个方向:
l <- list(c(1, 9), c(2, 8), c(3, 7))
m <- do.call(rbind, l)
split(m, row(m))
split(m, col(m))
## > split(m, row(m))
## $`1`
## [1] 1 9
##
## $`2`
## [1] 2 8
##
## $`3`
## [1] 3 7
## > split(m, col(m))
## $`1`
## [1] 1 2 3
##
## $`2`
## [1] 9 8 7https://stackoverflow.com/questions/40856504
复制相似问题