Using apply with a different function argument for each element's evaluation

后端 未结 2 1026
感动是毒
感动是毒 2021-01-28 06:20

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

2条回答
  •  盖世英雄少女心
    2021-01-28 06:52

    In this specific case, just roll the "est" values out to a matrix that matches the "true" values. Then you can subtract matrices (which R will automatically do componentwise) and use apply(), or here, colMeans():

    > true <- matrix(1:5, nrow = 10, ncol = 3, byrow = TRUE)
    > est <- matrix(1:3,nrow=nrow(true),ncol=ncol(true),byrow=TRUE)
    > sqrt(colMeans((true-est)^2))
    [1] 2.449490 1.732051 1.414214
    > 
    

    In more general cases involving lists, mapply() may be helpful.

提交回复
热议问题