Zip / unzip to R

I am looking for functions like zip / unzip in functional programming languages ​​(e.g. Haskell, Scala).

Haskell reference examples . Country:

Input: zip [1,2,3] [9,8,7]
Output: [(1,9),(2,8),(3,7)]

Unpack:

Input: unzip [(1,2),(2,3),(3,4)]
Output: ([1,2,3],[2,3,4])

In R, the input will look something like this. For clamping:

l1 <- list(1,2,3)
l2 <- list(9,8,7)
l <- Map(c, l1, l2)

To unpack:

tuple1 <- list(1,2)
tuple2 <- list(2,3)
tuple3 <- list(3,4)
l <- Map(c, tuple1, tuple2, tuple3)

Is there a built-in solution / library in R that implements these methods? (FP functions have quite a few names - searching for zip / unzip and R only gave me results for compressing / decompressing files.)

+4
source share
2 answers

purrr package tries to provide many FP primitives. purrrThe zip version is called 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() also works with your second (unzipped) example.

+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
+1

Source: https://habr.com/ru/post/1662209/


All Articles