这将使用相同的方法重新调整矩阵
normalize <- function(x) {
x <- sweep(x, 2, apply(x, 2, mean)) # retrive the mean from each column
2* sweep(x, 2, apply(x, 2, function(y) max(y)-min(y)), "/")
}
}
编辑
按照评论中的建议使用colMeans
当然更快
normalize <- function(x) {
aa <- colMeans(x)
x <- sweep(x, 2, aa) # retrive the mean from each column
2* sweep(x, 2, apply(x, 2, function(y) max(y)-min(y)), "/")
}
A <- matrix(1:24, ncol=3)
> normalize(A)
[,1] [,2] [,3]
[1,] -1.0000000 -1.0000000 -1.0000000
[2,] -0.7142857 -0.7142857 -0.7142857
[3,] -0.4285714 -0.4285714 -0.4285714
[4,] -0.1428571 -0.1428571 -0.1428571
[5,] 0.1428571 0.1428571 0.1428571
[6,] 0.4285714 0.4285714 0.4285714
[7,] 0.7142857 0.7142857 0.7142857
[8,] 1.0000000 1.0000000 1.0000000
scale
使用基础包的功能进行编辑
scale(A,center=TRUE,scale=apply(A,2,function(x) 0.5*(max(x)-min(x))))
[,1] [,2] [,3]
[1,] -1.0000000 -1.0000000 -1.0000000
[2,] -0.7142857 -0.7142857 -0.7142857
[3,] -0.4285714 -0.4285714 -0.4285714
[4,] -0.1428571 -0.1428571 -0.1428571
[5,] 0.1428571 0.1428571 0.1428571
[6,] 0.4285714 0.4285714 0.4285714
[7,] 0.7142857 0.7142857 0.7142857
[8,] 1.0000000 1.0000000 1.0000000