【问题标题】:R : Check whether particular number is in the listR : 检查特定号码是否在列表中
【发布时间】:2013-06-04 00:50:42
【问题描述】:

这是我的情况:

我有一个名为 sc

的列表
> sc
[[1]]
 [1]  1  6 11 16 21 26 31 36 41 46 51 52

[[2]]
 [1]  2  7 12 17 22 27 32 37 42 47 53 54

[[3]]
 [1]  3  8 13 18 23 28 33 38 43 48 55 56

[[4]]
 [1]  4  9 14 19 24 29 34 39 44 49 57 58

[[5]]
 [1]  5 10 15 20 25 30 35 40 45 50 59 60

[[6]]
[1] 61 62 63 64 65 66

然后我想检查8是否在sc[k] (k=1:6)中。

如何编码呢?我尝试使用 for 但不工作。

【问题讨论】:

    标签: r list for-loop


    【解决方案1】:

    所有这些都应该工作:

    sapply(sc, `%in%`, x = 8)
    sapply(sc, is.element, el = 8)
    mapply(`%in%`, 8, sc)
    mapply(is.element, 8, sc)
    

    这些都返回TRUEFALSE的相同向量:每个列表元素是否包含8。如果您想要的是找到8 的此类索引(k),只需将其包装为which,例如:

    which(sapply(sc, `%in%`, x = 8))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2013-10-30
      • 2013-01-14
      • 1970-01-01
      • 2022-12-11
      相关资源
      最近更新 更多