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

查看:67
本文介绍了对每个元素的评估使用对不同的函数参数应用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天全站免登陆