【发布时间】:2016-09-23 12:48:07
【问题描述】:
我是 R 新手,因此我对应用函数不熟悉。我在任何地方都没有找到这个问题的答案,尽管我有一种(不那么优雅的)解决方法。
考虑一下这个伪代码:
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 函数)而不必为同一件事创建很多副本?
感谢您的建议。
【问题讨论】:
标签: r apply lapply sapply mapply