将特定于列表的截止值应用于嵌套列表中的各个向量
我有一个嵌套列表,have_list
。中心是一个包含四个整数向量的列表:a
、b
、c
、d
。
对于 a
、b
、c
、d
,每个都有一个唯一的 cutoff
值。我想找到当整数大于相关截止值时的第一个位置。
如果广告具有相同的截止
,我可以通过以下方式执行此操作:
rapply(have_list, function(x) which.max(x > cutoff), how = "list")
我的具体问题是如何在没有 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)))
所需数据
want_list <- list(Outer1 = list(a = 2, b = 2, c = 1, d = 1),
Outer2 = list(a = 1, b = 4, c = 4, d = 1))
I have a nested list, have_list
. At the center is a list with four vectors of integers, a
, b
, c
, d
.
For a
, b
, c
, d
, each has a unique cutoff
value. I would like to find the first positions when the integer is greater than the relevant cutoff value.
I can do this if a-d had the same cutoff
by:
rapply(have_list, function(x) which.max(x > cutoff), how = "list")
My specific question is how to use the respective cutoff values for a-d, without for
loops, if possible. I can't seem to find anything on the internet or SO, though apologies if I overlooked a previous question.
Sample data
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)))
Desired data
want_list <- list(Outer1 = list(a = 2, b = 2, c = 1, d = 1),
Outer2 = list(a = 1, b = 4, c = 4, d = 1))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
lapply
在“外部”列表中移动,并使用Map
将每个内部列表与相应的截止值进行比较:这是
str
此输出的:You can use
lapply
to move through the "Outer" lists, andMap
to compare each inner list to the corresponding cutoff:Here is the
str
of this output:像这样的东西怎么样:
输出:
How about something like this:
Output:
另一种可能的解决方案基于 purrr::map 和 purrr::map2:
Another possible solution, based on
purrr::map
andpurrr::map2
:对于任意嵌套的列表,您还可以在
rrapply
包中使用rrapply()
,它可以访问正在评估的列表元素的名称:For abritrarily nested lists, you can also use
rrapply()
in therrapply
-package, which can access the name of the list element under evaluation: