对每个元素的评估使用具有不同函数参数的 apply [英] Using apply with a different function argument for each element's evaluation

查看:24
本文介绍了对每个元素的评估使用具有不同函数参数的 apply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个矩阵,mat.

Let's say I have a matrix, mat.

mat <- matrix(1:5, nrow = 10, ncol = 3, byrow = TRUE)

而且我有一些我想应用的函数,在这种情况下是按列应用的.

And I have some sort of function that I want to apply, in this case by column.

getRMSE <- function(true, est) {
    sqrt(mean((true - est)^2))
}

(这个函数只是最近的一个例子,但我已经遇到过至少 5 次完全相同的难题.)

(This function is just the most recent example, but I've had this exact same conundrum at least 5 more times.)

如果要在矩阵上应用函数,请使用 apply.但是,如果您想在应用中对 'x' 具有不同值的矩阵应用函数怎么办?

If you want to apply a function over a matrix, you use apply. But what if you want to apply a function over a matrix with different values for 'x' in the apply?

在这种情况下,目标是 apply 执行与此等效的操作:

In this case, the goal would be that apply would perform the equivalent of this:

getRMSE(mat[,1], 1)
getRMSE(mat[,2], 2)
getRMSE(mat[,3], 3)

但是在将向量作为函数的补充参数时,我总是遇到问题.显然

But I always run into problems when giving a vector as a supplementary argument to the function. Obviously

apply(mat, 2, getRMSE, c(1,2,3))

不会起作用,因为它也会循环使用列中的数字.但是

isn't going to work, because it will recycle the numbers within the columns, too. But

apply(mat, 2, getRMSE, rep(c(1,2,3), 25)) 

也不起作用,我认为至少有一个镜头.

also doesn't work, which I thought at least had a shot.

推荐答案

您可以使用 mapply 其中 x 将是您的矩阵列,而 y常量.我没有费心将矩阵转换为列表,所以我必须在函数内部使用 unlist.

You could use mapply where x would be your matrix column, and y the constant. I didn't bother with converting the matrix into a list the smart way, so I have to use unlist inside the function.

mat <- matrix(1:5, nrow = 10, ncol = 3, byrow = TRUE)

mat.list <- apply(mat, MARGIN = 2, FUN = list)

mapply(FUN = function(x, y) {
  sqrt(mean((unlist(x) - y)^2))
}, x = mat.list, y = list(1, 2, 3))

[1] 2.449490 1.732051 1.414214

这篇关于对每个元素的评估使用具有不同函数参数的 apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆