gpt4 book ai didi

r - 基于另一个列表计算列表中的元素

转载 作者:行者123 更新时间:2023-12-04 02:56:06 25 4
gpt4 key购买 nike

我有两个如下所示的列表:

mylist <- list(a=c(1:5), 
b = c(5:12),
c = c(2:8))

list.id <- list(a=2, b=8, c=5)

我想统计 mylist 中高于 list.id 中相应元素的元素的数量,并将结果除以 length。我写了这个函数。

perm.fun <- perm.fun2 = function(x,y){length(which(x[[i]] < y[[i]]))/length(x[[i]])}

但是,当我这样做时:lapply(mylist, perm.fun, list.id) 我没有获得预期的结果。

谢谢

最佳答案

使用 lapply,您需要循环索引(123),因此它们可用于从 mylistlist.id 中提取元素:

perm.fun <- function(i, x, y) mean(x[[i]] > y[[i]])
lapply(seq_along(mylist), perm.fun, mylist, list.id)

但是 mapply 是完成该任务的更好工具。来自文档:

mapply applies FUN to the first elements of each ... argument, the second elements, the third elements, and so on.

所以你的代码可以是:

mapply(function(x, y) mean(x > y), mylist, list.id)
# a b c
# 0.6000000 0.5000000 0.4285714

关于r - 基于另一个列表计算列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com