【问题标题】:zip/unzip functions in RR中的压缩/解压缩函数
【发布时间】:2016-11-29 10:19:43
【问题描述】:

我正在寻找函数式编程语言(例如 Haskell、Scala)中的 zip/unzip 等函数。

Examples from the Haskell reference。邮编:

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 只给我压缩/解压缩文件的结果。)

【问题讨论】:

  • Map(c, l1, l2)Map(c, tuple1, tuple2, tuple3) 我认为 - 你的 R 示例有点令人困惑。
  • @thelatemail 谢谢,我相应地更新了问题。
  • 好吧,我认为答案是Map 函数,如果你满意的话。随意在下面回答您自己的问题:-)

标签: r functional-programming


【解决方案1】:

purrr package 试图提供很多 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)  ## TRUE

transpose() 也适用于您的第二个(解压缩)示例。

【讨论】:

  • 很高兴在一个月前的视频中看到这个,但不记得它所在的包裹。+1
  • 如果我正确理解了这个问题(可疑),我想应该是l %&gt;% transpose() %&gt;% simplify_all()
【解决方案2】:

我不认为这正是你所追求的,但如果它是等长向量,你可以符合一个数组,然后对任一方向使用 split:

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 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多