Normalization function in R

I have a matrix that I want to convert, so that every function in the converted dataset has a value of 0 and a variance of 1.

I tried using the following code:

scale <- function(train, test) 
{   
trainmean <- mean(train)
trainstd <- sd(train)
xout <- test
for (i in 1:length(train[1,])) {
    xout[,i] = xout[,i] - trainmean(i)
}
for (i in 1:lenght(train[1,])) {
    xout[,i] = xout[,i]/trainstd[i]
}

}
invisible(xout)

normalized <- scale(train, test)

This, however, does not work for me. Am I on the right track?

Edit: I am very new to the syntax!

+4
source share
2 answers

You can use the built-in function for this scale.

Here is an example where we fill the matrix with random homogeneous variations between 0 and 1 and center and scale them to have an average value of 0 and a unit of standard deviation:

m <- matrix(runif(1000), ncol=4)    
m_scl <- scale(m)

Confirm that the column value is 0 (within the tolerance) and their standard deviations are 1:

colMeans(m_scl)
# [1] -1.549004e-16 -2.490889e-17 -6.369905e-18 -1.706621e-17

apply(m_scl, 2, sd)
# [1] 1 1 1 1

. ?scale.

, :

my_scale <- function(x) {
  apply(m, 2, function(x) {
    (x - mean(x))/sd(x)
  }) 
}

m_scl <- my_scale(m)

, , ,

my_scale <- function(x) sweep(sweep(x, 2, colMeans(x)), 2, apply(x, 2, sd), '/')
+9

, apply , , :

m = matrix(rnorm(5000, 2, 3), 50, 100)

m_centred = m - m%*%rep(1,dim(m)[2])%*%rep(1, dim(m)[2])/dim(m)[2]
m_norm = m_centred/sqrt(m_centred^2%*%rep(1,dim(m)[2])/(dim(m)[2]-1))%*%rep(1,dim(m)[2])

## Verirication
rowMeans(m_norm)
apply(m_norm, 1, sd)

( , )

+2

All Articles