问题描述
如何对每行的数据进行缩放/标准化(观察)?像 [-1:1] 之类的东西,比如 z 分数?
我看过以前的帖子,其中涉及整个数据集的标准化https://stats.stackexchange.com/questions/178626/how-to-normalize-data-between-1-and-1 ,但 id 喜欢对每一行进行归一化,以便它们可以绘制在同一个箱线图中,因为它们在 x 轴上都显示相同的模式。
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()
解决方法
根据您分享的链接,您可以使用 apply
使用相应的函数在 [-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()
控制台输出:
,如果将其旋转更长的时间,您可以根据您的观察和比例进行分组:
df %>%
pivot_longer(cols = !Obs,values_to = 'Value') %>% group_by(Obs) %>%
mutate(z=as.numeric(scale(Value))) %>%
ggplot(aes(x=count,y=z))+geom_boxplot()
或者在基础 R 中,只需执行以下操作:
boxplot(t(scale(t(df[,-1]))))