R将列表转换成成对的连续元素

时间:2018-10-04 15:29:29

标签: r

带有列表

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

我正在寻找一个列出列表中所有可能的后继者对的转换

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)

所以当列表包含N个元素时,我希望有N-1对-Thx

1 个答案:

答案 0 :(得分:7)

你可以做...

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"

或者,...

embed(lst, 2)

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