1

This is sample of my matrix and my code. I want to rescale my dataframe so that the each row has magnitude 1. I'm new to r and in the tutorial the instructor said "divide each element of a row by the magnitude of the row." however I'm not sure how can I get the magnitude of the row or rescale the dataframe. So I tried to use apply() however after testing my rescale using sqrt(sum(sc_mydata[r,]^2)) I didn't get 1 and I the result of x should be 1

#dataframe
myData <- myData[1:12]

#transpose
x <- t(myData)

#rescale the data
sc_mydata = apply(x[-1,], 1, scale)

#test rescale 
for (r in 1:nrow(sc_mydata)) {
  #test rescale if this  is equal to 1 then the rescaling worked 
  x <- sqrt(sum(sc_mydata[r,]^2))
  
  }

2 Answers2

2

If by "the magnitude of the row" your instructor means "the sum of the row", this works:


sc_mydata <- apply(x, 1, function(x) x / sum(x, na.rm = TRUE))
sc_mydata <- t(sc_mydata)


For some reason, the row-wise apply() function transposes the data frame, so I had to transpose it back. I don't use apply much (prefer the tidyverse tools to base R) so idk why that happens.

Adam B.
  • 788
  • 5
  • 14
  • The sample data suggests `NA` values, you might need `sum(x, na.rm=TRUE)`. – r2evans Apr 12 '20 at 21:37
  • @AdamB. thank you for your help I think it's working can I ask how can I confirm if the rescale work I tried to apply sqrt(sum(sc_mydata[r,]^2)) but it didn't give me 1 for each row – geekPinkFlower Apr 14 '20 at 19:51
2

We could do this in a vectorized way with rowSums

x/rowSums(x)
akrun
  • 874,273
  • 37
  • 540
  • 662