gpt4 book ai didi

r - 如何指定在 R 的 mapply 中迭代哪些参数

转载 作者:行者123 更新时间:2023-12-02 07:18:47 36 4
gpt4 key购买 nike

我是 R 新手,因此我对 apply 函数也不熟悉。尽管我有一种(不太优雅的)解决方法,但我在任何地方都没有找到这个问题的答案。

考虑这个虚拟代码:

my.fun <- function(vector1, vector2, vector3 = NULL) {
# do stuff with the vectors
}

list1 <- mapply(FUN = my.fun, arg1, arg2, list(arg3), SIMPLIFY = FALSE)

假设 arg1 和 arg2 是我想在 mapply 函数内迭代的列表(长度相同),但 arg3 只是一个我想在 my.fun() 中使用而不进行迭代的向量。我的问题是:如何在所有 mapply 函数迭代中将 arg3 放入 my.fun() 中?澄清一下,my.fun() 中的 vector3 应该等于 my.fun() 之外的 arg3。

执行此操作的一种方法是:

list1 <- mapply(FUN = my.fun, arg1, arg2, rep(list(arg3), length(arg1)), SIMPLIFY = FALSE)

但看起来应该有一种更优雅的方式。

有没有办法指定哪些参数被迭代,哪些参数不被迭代?或者做同样的事情(使用 apply-family 函数)而不必创建同一事物的大量副本?

感谢您的建议。

最佳答案

maply() 有一个 MoreArgs= 参数专门用于此目的。

例如:

par(mfcol=c(2,2), ann=FALSE, mar=c(1,1,1,1))
mapply(plot, x=1:4, y=4:1, col=1:4,
MoreArgs=list(xlim=c(1,4), ylim=c(1,4), pch=16, cex=3))

enter image description here

关于r - 如何指定在 R 的 mapply 中迭代哪些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37445192/

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