Ecg
Ecg

Reputation: 942

Normalize data per row in R

How can I scale/normalize my data per row (Observations)? Something like [-1:1] like a z score?

I have seen previous post which involve normalization of the whole dataset like this https://stats.stackexchange.com/questions/178626/how-to-normalize-data-between-1-and-1 , but id like to normalise per row so they can be plotted in a same box plot as they all show same pattern across x-axis.

Obs <- c("A", "B", "C")
count1 <- c(100,15,3)
count2 <- c(250, 30, 5)
count3 <- c(290, 20, 8)
count4<- c(80,12, 2 )
df <- data.frame(Obs, count1, count2, count3, count4)
dff<- df %>% pivot_longer(cols = !Obs, names_to = 'count', values_to = 'Value') 
ggplot(dff, aes(x = count, y = Value)) +
    geom_jitter(alpha = 0.1, color = "tomato") + 
    geom_boxplot()

enter image description here

Upvotes: 2

Views: 1879

Answers (2)

StupidWolf
StupidWolf

Reputation: 46938

If you pivot it longer, you can group by your observations and scale:

df %>% 
pivot_longer(cols = !Obs, names_to = 'count', values_to = 'Value') %>% group_by(Obs) %>% 
mutate(z=as.numeric(scale(Value))) %>% 
ggplot(aes(x=count,y=z))+geom_boxplot()

enter image description here

Or in base R, just do:

boxplot(t(scale(t(df[,-1]))))

enter image description here

Upvotes: 2

AlSub
AlSub

Reputation: 1155

Based on the link you shared, you can use apply to use the corresponding function to rescale dataframe over [-1,1].

library(scales)
library(ggplot2)
library(tidyr)

Obs <- c("A", "B", "C")
count1 <- c(100,15,3)
count2 <- c(250, 30, 5)
count3 <- c(290, 20, 8)
count4<- c(80,12, 2 )

df <- data.frame(count1, count2, count3, count4)

df <- as.data.frame(t(apply(df, 1, function(x)(2*(x-min(x))/(max(x)-min(x)))- 1)))

df <- cbind(Obs, df)

dff<- df %>% 
       tidyr::pivot_longer(cols = !Obs, names_to = 'count', values_to = 'Value') 


ggplot(dff, aes(x = count, y = Value)) +
     geom_jitter(alpha = 0.1, color = "tomato") + 
     geom_boxplot()


Console output:

enter image description here

Upvotes: 3

Related Questions