在列表中显示相邻成员

Show adjacent members in a list

我想根据匹配检查列表中的相邻元素。例如,在随机排列的字母列表中,我想知道 m 的相邻字母是什么。我目前的解决方案是:

library(stringr)
ltrs <- sample(letters)
ltrs[(str_which(ltrs,'m')-2):(str_which(ltrs,'m')+2)]
[1] "j" "f" "m" "q" "a"

对我来说,str_which() 的重复感觉没有必要。有没有更简单的方法可以达到同样的效果?

首先,我使用种子重新生成随机数据以实现可重复性:

set.seed(42)
ltrs <- sample(letters)
ltrs
#  [1] "q" "e" "a" "j" "d" "r" "z" "o" "g" "v" "i" "y" "n" "t" "w" "b" "c" "p" "x"
# [20] "l" "m" "s" "u" "h" "f" "k"

使用-2:2然后(谨慎地)删除那些小于1或大于向量长度的:

ind <- -2:2 + which(ltrs == "m")
ind <- ind[0 < ind & ind < length(ltrs)]
ltrs[ind]
# [1] "x" "l" "m" "s" "u"

如果您的目标不止一个(不仅仅是 "m"),那么我们可以使用不同的方法。

ind <- which(ltrs %in% c("m", "f"))
ind <- lapply(ind, function(z) { z <- z + -2:2; z[0 < z & z <= length(ltrs)]; })
ind
# [[1]]
# [1] 19 20 21 22 23
# [[2]]
# [1] 23 24 25 26
lapply(ind, function(z) ltrs[z])
# [[1]]
# [1] "x" "l" "m" "s" "u"
# [[2]]
# [1] "u" "h" "f" "k"

或者,如果您不介意将它们分组,我们可以试试这个:

ind <- which(ltrs %in% c("m", "f"))
ind <- unique(sort(outer(-2:2, ind, `+`)))
ind <- ind[0 < ind & ind <= length(ltrs)]
ltrs[ind]
# [1] "x" "l" "m" "s" "u" "h" "f" "k"

如果没有重复,可以试试下面的代码

ltrs[seq_along(ltrs)%in% (which(ltrs=="m")+(-2:2))]

否则

ltrs[seq_along(ltrs) %in% c(outer(which(ltrs == "m"), -2:2, `+`))]

你也可以使用slider::slide函数(使用@r2evans提供的数据):

slider::slide(ltrs, ~ .x, .before = 2, .after = 2)[[which(ltrs == "m")]]
# [1] "x" "l" "m" "s" "u"

slider::slide(ltrs, ~ .x, .before = 2, .after = 2)[which(ltrs %in% c("m","f"))]
# [[1]]
# [1] "x" "l" "m" "s" "u"
#
# [[2]]
# [1] "u" "h" "f" "k"