将特定于列表的截止值应用于嵌套列表中的各个向量

jps*_*ith 6 r list nested-lists

我有一个嵌套列表,have_list. 中心是一个包含四个整数向量的列表,a, b, c, d

对于abcd,每个都有唯一的cutoff值。我想找到当整数大于相关截止值时的第一个位置。

如果广告有相同的内容,我可以cutoff通过以下方式执行此操作:

rapply(have_list, function(x) which.max(x > cutoff), how = "list")
Run Code Online (Sandbox Code Playgroud)

我的具体问题是,如果可能的话,如何在没有for循环的情况下使用广告的相应截止值。我似乎在互联网上找不到任何东西,但如果我忽略了之前的问题,我深表歉意。

样本数据

cutoff <- c(a = 5, b = 17, c = 11, d = 7)

set.seed(05062020)
have_list <- list(Outer1 = list(a = sample(1:25, 10),
                                b = sample(1:25, 10),
                                c = sample(1:25, 10),
                                d = sample(1:25, 10)),
                  Outer2 = list(a = sample(1:25, 10),
                                b = sample(1:25, 10),
                                c = sample(1:25, 10),
                                d = sample(1:25, 10)))
Run Code Online (Sandbox Code Playgroud)

所需数据

want_list <- list(Outer1 = list(a = 2, b = 2, c = 1, d = 1),
                  Outer2 = list(a = 1, b = 4, c = 4, d = 1))
Run Code Online (Sandbox Code Playgroud)

jdo*_*res 1

您可以使用lapply在“外部”列表中移动,并将Map每个内部列表与相应的截止值进行比较:

lapply(have_list, \(x) {Map(\(lst, cuts) {
  return(which(lst > cuts)[1])
}, x, cutoff)})
Run Code Online (Sandbox Code Playgroud)

这是str此输出的:

List of 2
 $ Outer1:List of 4
  ..$ a: int 2
  ..$ b: int 2
  ..$ c: int 1
  ..$ d: int 1
 $ Outer2:List of 4
  ..$ a: int 1
  ..$ b: int 4
  ..$ c: int 4
  ..$ d: int 1
Run Code Online (Sandbox Code Playgroud)