gpt4 book ai didi

r - 标准化 R 中每行的数据

转载 作者:行者123 更新时间:2023-12-02 19:02:41 29 4
gpt4 key购买 nike

如何缩放/规范化每行数据(观察)?像 [-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()

enter image description here

最佳答案

根据您共享的链接,您可以使用 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()


控制台输出:

enter image description here

关于r - 标准化 R 中每行的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65365248/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com