繁体   English   中英

R 到 Python t.test function 转换

[英]R to Python t.test function conversion

有人可以帮我将这个 R t.test function 转换为 python 吗? r 代码: t.test(y, mu = 85, paired = FALSE, var.equal =TRUE, alternative = "greater)

您可能会发现此博客很有用: https://www.reneshbedre.com/blog/ttest.html

下面是使用 bioinfokit package 进行转换的示例,但您可以使用 scipy 之一。

# Perform one sample t-test using bioinfokit,
# Doc: https://github.com/reneshbedre/bioinfokit

from bioinfokit.analys import stat
from bioinfokit.analys import get_data
df = get_data("t_one_samp").data #replace this with your data file
res = stat()
res.ttest(df=df, test_type=1, res='size', mu=5,evar=True)
print(res.summary)

输出:

One Sample t-test 

------------------  --------
Sample size         50
Mean                 5.05128
t                    0.36789
Df                  49
P-value (one-tail)   0.35727
P-value (two-tail)   0.71454
Lower 95.0%          4.77116
Upper 95.0%          5.3314
------------------  --------

您正在针对总体平均值mu测试单个样本x ,因此来自 SciPy 的相应 function 是scipy.stats.ttest_1samp 当第二个样本y没有给t.test时, var_equalpaired不相关,所以唯一要处理的其他参数是alternative ,并且SciPy function 也采用了alternative参数。 所以 Python 代码是

    from scipy.stats import ttest_1samp

    result = ttest_1samp(y, mu, alternative='greater')

请注意, ttest_1samp仅返回 t 统计量 ( result.statistic ) 和 p 值 ( result.pvalue )。

例如,这里是 R 中的计算:

> x = c(3, 1, 4, 1, 5, 9)
> result = t.test(x, mu=2, alternative='greater')
> result$statistic
      t 
1.49969 
> result$p.value
[1] 0.09699043

这是Python中对应的计算

In [14]: x = [3, 1, 4, 1, 5, 9]

In [15]: result = ttest_1samp(x, 2, alternative='greater')

In [16]: result.statistic
Out[16]: 1.499690178660333

In [17]: result.pvalue
Out[17]: 0.0969904256712105

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM