gpt4 book ai didi

R:使用 ddply 按组进行 cor.test

转载 作者:行者123 更新时间:2023-12-05 09:22:41 24 4
gpt4 key购买 nike

我正在尝试计算数据框中两个数字列之间的相关性,以获得每个因子水平。这是一个示例数据框:

concentration <-(c(3, 8, 4, 7, 3, 1, 3, 3, 8, 6))
area <-c(0.5, 0.9, 0.3, 0.4, 0.5, 0.8, 0.9, 0.2, 0.7, 0.7)
area_type <-c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B")
data_frame <-data.frame(concentration, area, area_type)

在这个例子中,我想为 area_type 的每个级别计算浓度和面积之间的相关性。我想使用 cor.test 而不是 cor,因为我想要 p 值和 kendall tau 值。我尝试使用 ddply 来做到这一点:

ddply(data_frame, "area_type", summarise,
corr=(cor.test(data_frame$area, data_frame$concentration,
alternative="two.sided", method="kendall") ) )

但是,我对输出有疑问:它的组织方式与正常的 Kendall cor.test 输出不同,后者表示 z 值、p 值、备择假设和 tau 估计。取而代之的是,我得到了下面的输出。我不知道输出的每一行表示什么。此外,area_type 的每个级别的输出值都相同。

  area_type                                         corr
1 A 0.3766218
2 A NULL
3 A 0.7064547
4 A 0.1001252
5 A 0
6 A two.sided
7 A Kendall's rank correlation tau
8 A data_frame$area and data_frame$concentration
9 B 0.3766218
10 B NULL
11 B 0.7064547
12 B 0.1001252
13 B 0
14 B two.sided
15 B Kendall's rank correlation tau
16 B data_frame$area and data_frame$concentration

我对 ddply 做错了什么?还是有其他方法可以做到这一点?谢谢。

最佳答案

您可以添加一个名为 corr 的附加列。另外,您的语法有点不正确。 . 指定变量来自您指定的数据框。然后删除 data_frame$ 否则它将使用整个数据框:


ddply(data_frame,.(area_type),总结,
corr=(cor.test(面积,浓度,
alternative="two.sided", method="kendall")), name=names(corr) )

给出:

   area_type                           corr        name
1 A -0.285133 statistic
2 A NULL parameter
3 A 0.7755423 p.value
4 A -0.1259882 estimate
5 A 0 null.value
6 A two.sided alternative
7 A Kendall's rank correlation tau method
8 A area and concentration data.name
9 B 6 statistic
10 B NULL parameter
11 B 0.8166667 p.value
12 B 0.2 estimate
13 B 0 null.value
14 B two.sided alternative
15 B Kendall's rank correlation tau method
16 B area and concentration data.name

statistic 是 z 值,estimate 是 tau 估计值。

编辑:你也可以这样做只拉你想要的东西:

corfun<-function(x, y) {
corr=(cor.test(x, y,
alternative="two.sided", method="kendall"))
}

ddply(data_frame, .(area_type), summarise,z=corfun(area,concentration)$statistic,
pval=corfun(area,concentration)$p.value,
tau.est=corfun(area,concentration)$estimate,
alt=corfun(area,concentration)$alternative
)

给出:

area_type z pval tau.est alt
1 A -0.285133 0.7755423 -0.1259882 双面
2 B 6.000000 0.8166667 0.2000000 双面

关于R:使用 ddply 按组进行 cor.test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964947/

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