I am trying to normalize all rows of my matrix data at once within range 0 and 1. But I don\'t know how to do it.. For example, I want to normalize each \"obs1\", \"obs2\",
To normalize for each row, you can use apply
and then subtract the minimum from each column and divide by the difference between maximum and minimum:
t(apply(mydata, 1, function(x)(x-min(x))/(max(x)-min(x))))
gives you
a b c d e
obs1 0.05553973 1.0000000 0.8889038 0.2777796 0.0000000
obs2 0.00000000 1.0000000 0.6805144 0.4848262 0.3945675
obs3 0.00000000 0.3289472 1.0000000 0.8605280 0.8736849
What happens is that you apply the function
function(x){
(x-min(x))/(max(x)-min(x))
}
to each row of your data frame.
You could use the apply with rescale as the following:
apply(mydata, 1, rescale)
where the second argument 1
tells apply to work with rows.
The default range is [0, 1] but a custom range can be specified with the to
argument that will be forwarded to the rescale
function:
apply(mydata, 1, rescale, to=c(1,2))
Dependecy:
if(!require(scales)){
install.packages("scales", dependencies=TRUE)
library(scales)
}
for(i in 2:length(mydata[1,])){
mydata[,i] <- prop.table(mydata[,i])
}
Normalized matrix will be updated in mydata