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

后端 未结 2 1147
感动是毒
感动是毒 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 07:10

    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
    

提交回复
热议问题