简体   繁体   English

R将列表转换为连续元素对

[英]R transform a list into pairs of successive elements

With the list 随着名单

lst <- list("a","b","c","a","b","b")

I'm looking for a transformation listing all possible pairs of successors from the list 我正在寻找一个转型,列出列表中所有可能的后继对

a b    ( 1st and 2nd elements)
b c    ( 2nd and 3rd elements)
c a    ( 3rd and 4th elements)
a b    ( 4th and 5th elements)
b b    ( 5th and 6th elements)

so when the list contains N elements, I'm expecting N-1 pairs - Thx 所以当列表包含N个元素时,我期待N-1对 - Thx

You can do... 你可以做...

Map(c, head(lst, -1), tail(lst, -1))

[[1]]
[1] "a" "b"

[[2]]
[1] "b" "c"

[[3]]
[1] "c" "a"

[[4]]
[1] "a" "b"

[[5]]
[1] "b" "b"

Alternately, ... 或者......

embed(lst, 2)

     [,1] [,2]
[1,] "b"  "a" 
[2,] "c"  "b" 
[3,] "a"  "c" 
[4,] "b"  "a" 
[5,] "b"  "b" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM