Loops to normalise data

Viewed 178

Here's a small dataset

RWC<-as.data.frame(matrix(1:9,ncol=3))
RWC
V1 V2 V3
 1  4  7  
 2  5  8  
 3  6  9  

I'm trying to normalise by suming the rows separately and have the original number divide by the sum. This should lead to this (I do not need the rounding, this is just for convenience).

V1    V2    V3
0.08  0.33  0.58  
0.13  0.33  0.53  
0.16  0.33  0.50 

I've so far written

for(i in 3:nrow(RWC)){
  normalise <- sum(row[3:ncol])
  RWC <- ()
}

I'm stuck on trying to divide and give the value to the specific row and column, how would I do this?

3 Answers

The fast way to get the sum in each row is rowSums(RWC). Then just divide RWC by the result.

RWC <- RWC / rowSums(RWC)

We can use prop.table with margin as 1.

prop.table(as.matrix(RWC), 1)

#          V1     V2     V3
#[1,] 0.08333 0.3333 0.5833
#[2,] 0.13333 0.3333 0.5333
#[3,] 0.16667 0.3333 0.5000

prop.table is wrapper around sweep

sweep(RWC, 1, rowSums(RWC), `/`)

Without using a for loop, you can use apply function:

apply(RWC,1, function(x) round(x/sum(x),2))

   [,1] [,2] [,3]
X1 0.08 0.13 0.17
X2 0.33 0.33 0.33
X3 0.58 0.53 0.50
Related