【问题标题】:Test whether position x is between any start (i=1 to i=max) and end (i=1 to i=max) positions stored in lists测试位置 x 是否在存储在列表中的任何开始(i=1 到 i=max)和结束(i=1 到 i=max)位置之间
【发布时间】:2021-03-10 22:54:13
【问题描述】:

我有一个简单的数据框,其中指定了列表中的开始和结束位置。这些开始和结束位置定义了 i 个区域。现在我想测试给定位置是否在这样的区域内,如果是,我需要知道在哪个区域 (i)。

这是一个简单的示例数据框:

start <- list(c(5,10,15), c(5) ,c(6,11),c(6,11))
end <- list(c(7,11,17), c(10), c(8,12),c(8,12))
imax <- c(3,1,2,2)
position <- c(11,6,9,8)

example <- data.frame(start = I(start), end = I(end), imax = imax, position = position)

当我只有一个开始和结束位置时,没问题(如示例的第 2 行):

data.table::between(example$position[[1]], example$start[[1]], example$end[[1]])

[1] FALSE  TRUE FALSE

我怎样才能把它变成一个函数,对 example$start 和 example$end 中的每个元素(从 i=1 到 i=max)进行成对检查?

第二步是检索哪个区域 i(1 到 imax)这是 TRUE。

谢谢。

【问题讨论】:

    标签: r list dataframe vector


    【解决方案1】:

    听起来您可能正在寻找这样的功能。

    由于您的startend 是列表,您可以unlist。要成对检查每个元素,您可以循环遍历 startend 直到 imax

    假设您可以拥有多个区域,您可以在函数末尾返回一个列表(或其他内容)。

    my_fun <- function(x) {
      vec <- integer(0)
      start <- unlist(x[["start"]])
      end <- unlist(x[["end"]])
      for (i in 1:x[["imax"]]) {
        if (between(x[["position"]], start[i], end[i])) vec <- c(vec, i)
      }
      list(vec)
    }
    
    example$regions <- apply(example, 1, my_fun)
    

    输出

          start       end imax position regions
    1 5, 10, 15 7, 11, 17    3       11       2
    2         5        10    1        6       1
    3     6, 11     8, 12    2        9        
    4     6, 11     8, 12    2        8       1
    

    【讨论】:

    • 嘿,谢谢你!有用!上述问题实际上是一个更大问题的一部分。最终目标是在这里解决这个“桥牌游戏”:stackoverflow.com/questions/65003498/… 基本上,现在输入后只会丢失第 3 步)。您知道如何在 3) a)、b)、c)、d) 中对这些函数进行编程吗?从那以后我就被这个“桥牌游戏”困住了...... -.- 干杯
    猜你喜欢
    • 2020-05-24
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2014-02-22
    • 1970-01-01
    • 2015-05-24
    相关资源
    最近更新 更多