geekPinkFlower
geekPinkFlower

Reputation: 13

How can I rescale dataframe so each row have magnitude of 1 in R?

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))
  
  }

Upvotes: 1

Views: 1839

Answers (2)

Adam B.
Adam B.

Reputation: 1180

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.

Upvotes: 2

akrun
akrun

Reputation: 887058

We could do this in a vectorized way with rowSums

x/rowSums(x)

Upvotes: 1

Related Questions