[英]Apply with user defined functions
I have a user defined function that I am trying to use with apply on a matrix. 我有一个用户定义的函数,试图将其应用于矩阵。 Maybe the example will explain it better: 也许这个例子可以更好地解释它:
modFn<-function(x)
{
mod10 = x %% 10;
return(mod10)
}
mat = matrix(100:119, nrow = 5, ncol = 4)
apply(mat, 1, modFn)
It doesn't give me the output that I need. 它没有给我我需要的输出。 What am I doing wrong? 我究竟做错了什么?
The 1 in 1进
apply(mat, 1, modFn)
Indicates you are working by rows... and then the apply function returns a matrix which cols relate to your original rows... ie. 表示您正在按行工作...,然后apply函数返回一个矩阵,该列与您的原始行有关...即。 transposed. 转置。
Probably what you are thinking about is: 您可能正在考虑的是:
apply(mat, 2, modFn)
But this is the same as mat %% 10
as Stibu mentioned. 但这与Stibu提到的mat %% 10
相同。
(mat %% 10) == t (apply(mat, 1, modFn))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.