2016-11-29 537 views
4

我正在尋找諸如函數式編程語言(例如Haskell,Scala)中的zip/unzip函數。R中的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只給我壓縮/解壓縮文件的結果。)

+2

'地圖(C,L1, l2)'和'Map(c,tuple1,tuple2,tuple3)'我想 - 你的R例子有點混亂。 – thelatemail

+0

@thelatemail謝謝,我相應地更新了問題。 –

+0

嗯,我想如果你滿意的話,答案就是'Map'函數。請隨時回答您自己的問題:-) – thelatemail

回答

2

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()也適用於您的第二個(解壓縮)示例。

+0

尼斯在一個月後的視頻中看到了這一點,並且忘記了它的包裝。+1 –

+0

如果我正確地理解了這個問題(可疑),我認爲它會是'l%>%transpose()%> simplify_all_all()' – alistaire

1

我不認爲這正是你追求的,但如果它的長度相等的向量可以遵循一個數組,然後用拆分爲兩個方向:

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