【问题标题】:Use of mapply to transform a vector element-wise by vector with functions使用 mapply 通过带有函数的向量逐元素变换向量
【发布时间】:2013-08-23 16:58:01
【问题描述】:

mapply的使用有疑问。

考虑以下两种情况: 案例 1 显示了我希望做的简化示例。我使用 mapply 将向量 k 元素与存储在向量 trans 中的函数进行转换。这有效(related to this question

案例 2 中,我希望做类似的事情,但是,我想要额外的函数参数(这里,存储在 a 中)。但我可能想要 n 个函数参数。我在这个例子中得到的是一个 3x3 矩阵,预期结果在对角线上。我只想要对角线的计算输出。怎么样?

k <- seq(1:3)
# Case 1 -----------------------------------------------------------------------
trans <- c(function(x) x, function(x) 1/x, function(x) x^2)             
# transform vektors elementwise with functions in a "transform" vektor
ktrans   <- mapply(function(f, x) f(x), trans, k)

# 2 -----------------------------------------------------------------------
k <- seq(1:3)
a <- rep(2,3)
transa <- c(function(x,a) x*a, function(x,a) 1/x*a, function(x,a) x^2*a)
ktransa   <- mapply(function(f, x,a) f(x,a), transa, MoreArgs= list(x = k, a= a))

> diag(ktransa)
[1]  2  1 18

【问题讨论】:

  • 案例 1 不起作用,除非我删除 a,否则我会得到 Error in function (f, x) : unused argument(s) (dots[[3]][[1]])。你到底想做什么?在 case 2 中,您将一个向量输入到mapplysupposed 以输出一个矩阵,其中 k 中的每个 # 都以各种方式转换。即,3 个数字,每个数字经过 3 次变换 = 一个 3x3 矩阵。
  • 为什么不在函数调用中提供额外的参数?即 mapply(function(f, x) f(x, arg1, arg2, arg3), transa) ??
  • 我希望 mapply 返回当前 mapply 输出的诊断向量。即向量transa[i] 中的函数使用k[i]a[i] 作为参数,然后输出是一个向量。 i 从 1 到 length(transa)@Karl:这不是我在 case2 中所做的吗?

标签: r mapply


【解决方案1】:

解决方案:

我没有使用列表将参数发送给函数,而是明确地做到了:

# 3 --- Example with n arguments -----------------------------------
k <- seq(1:3)
a <- rep(2,3)
transa <- c(function(x,a) x*a, function(x,a) 1/x*a, function(x,a) x^2*a)
ktransa   <- mapply(function(f, x, a) f(x,a), transa,x = k , a = a)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多