gpt4 book ai didi

r - 根据组/类别执行多个配对的t检验

转载 作者:行者123 更新时间:2023-12-04 16:24:07 30 4
gpt4 key购买 nike

我被困在Rstudio中为多个类别执行t.tests。我想获得每种产品类型的t.test的结果,比较在线和离线价格。我有800多种产品类型,所以这就是为什么不想为每个产品组手动进行操作。

我有一个命名为data的数据框(超过200万行),如下所示:

> Product_type   Price_Online   Price_Offline   
1 A 48 37
2 B 29 22
3 B 32 40
4 A 38 36
5 C 32 27
6 C 31 35
7 C 28 24
8 A 47 42
9 C 40 36

理想情况下,我希望R将t.test的结果写入另一个称为product_types的数据帧中:
    > Product_type   
1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
800 ...

变成:
> Product_type   t         df       p-value   interval    mean of difference            
1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
800 ...

如果我所有产品类型都在不同的数据框中,这就是公式:
t.test(Product_A$Price_Online, Product_A$Price_Offline, mu=0, alt="two.sided", paired = TRUE, conf.level = 0.99)

必须有一个更简单的方法来执行此操作。否则,我需要制作800多个数据帧,然后执行t检验800次。

我尝试了使用列表和lapply进行操作,但到目前为止它不起作用。我还在多个列上尝试了t-Test:
https://sebastiansauer.github.io/multiple-t-tests-with-dplyr/

但是,最后,他仍然手动插入男性和女性(对我来说,超过800个类别)。

最佳答案

一种方法是使用by:

result <- by(data, data$Product_type, 
function(x) t.test(x$Price_Online, x$Price_offline, mu=0, alt="two.sided", paired = TRUE, conf.level = 0.99))

唯一的缺点是,通过返回列表,如果要将结果放入数据框,则必须对其进行转换:
df <- data.frame(t(matrix(unlist(result), nrow = 10)))

然后,您必须手动添加产品类型和列名称:
df$Product_type <- names(result)
names(df) <- names(result$A)

关于r - 根据组/类别执行多个配对的t检验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609694/

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