【问题标题】:when the iterable is NOT the first argument of the function当可迭代不是函数的第一个参数时
【发布时间】:2014-04-11 08:16:23
【问题描述】:

问题很简单,但我找不到答案。

我有myfun <- function(x, y)。我如何通过y 的列表来sapply 这个函数?

要申请x 我会这样做

iterables <- 1:10
sapply(iterables, myfun, y)

但我希望 iterables 改为 y。

【问题讨论】:

  • 你在找sapply(y, myfun, x=x)吗?
  • 实际上,我的函数有两个以上的参数。我无法手动指定所有其他参数。

标签: r apply sapply


【解决方案1】:

您有多种选择 - 例如。 sgibb 提到的一个依赖于 R 如何解释函数参数,即 myfun(y, x = x)myfun(x, y) 相同。

我更喜欢创建匿名函数,因为这样更容易理解发生了什么:

sapply(iterables, function(iter) myfun(x, iter))

【讨论】:

  • 如果myfun 有,比如说,5 个参数,我可以这样做吗? sapply(iterables, function(iter) myfun(x1, x2, x3, iter, x4)?
猜你喜欢
  • 2019-07-15
  • 2016-11-28
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-05
  • 2020-09-07
  • 2011-02-25
相关资源
最近更新 更多