【发布时间】:2021-12-29 13:04:03
【问题描述】:
有人可以帮我把这个 R t.test 函数转换成 python 吗?
r 代码:
t.test(y, mu = 85, paired = FALSE, var.equal =TRUE, alternative = "greater)
【问题讨论】:
-
还是想不通
标签: python r scipy statistics
有人可以帮我把这个 R t.test 函数转换成 python 吗?
r 代码:
t.test(y, mu = 85, paired = FALSE, var.equal =TRUE, alternative = "greater)
【问题讨论】:
标签: python r scipy statistics
您正在针对总体平均值 mu 测试单个样本 x,因此 SciPy 中的相应函数是 scipy.stats.ttest_1samp。当第二个样本y 没有给t.test 时,var_equal 和paired 不相关,所以唯一要处理的其他参数是alternative,SciPy 函数也需要一个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
【讨论】:
您可能会发现此博客很有用:https://www.reneshbedre.com/blog/ttest.html
这是一个使用 bioinfokit 包进行转换的示例,但您可以使用 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
------------------ --------
【讨论】: