![](/img/trans.png)
[英]Applying a function over consecutive pairs of list elements in R without loops
[英]R iterate over consecutive pairs in a list
假設我有以下向量:
v1 = c(1,2,3,4)
我需要以成對的方式迭代這個向量,比如(1,2), (2,3), (3,4)
。 對於 python,這里有一個解決此問題的方法: 遍歷列表中的所有連續項對。 在 R 中是否可以實現類似的解決方案?
我們可以在Map
中刪除第first
和last
元素並連接
Map(c, v1[-length(v1)], v1[-1])
#[[1]]
#[1] 1 2
#[[2]]
#[1] 2 3
#[[3]]
#[1] 3 4
或rbind
並使用asplit
asplit(rbind(v1[-length(v1)], v1[-1]), 2)
只需cbind
移位的向量。
cbind(v1[-length(v1)], v1[-1])
# [,1] [,2]
# [1,] 1 2
# [2,] 2 3
# [3,] 3 4
R 是矢量化的,不需要迭代。
通過將 2 替換為其他數字,這些解決方案都可以輕松推廣到大於 2 的 windows。
1) rollapply用你想使用的任何 function 替換toString
。
library(zoo)
rollapply(v1, 2, toString)
## [1] "1, 2" "2, 3" "3, 4"
1a)或創建一個 2 列矩陣,然后在第二步中對其進行迭代:
library(zoo)
m <- rollapply(v1, 2, c)
apply(m, 1, toString)
## [1] "1, 2" "2, 3" "3, 4"
2)嵌入或使用embed
。 這不使用任何包。
e <- embed(v1, 2)[, 2:1]
apply(e, 1, toString)
## [1] "1, 2" "2, 3" "3, 4"
使用embed
+ asplit
的基本 R 選項
> asplit(embed(v1,2)[,2:1],1)
[[1]]
[1] 1 2
[[2]]
[1] 2 3
[[3]]
[1] 3 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.