首页 > 解决方案 > 如何打印具有 2 个有效数字的 p 值?

问题描述

当我通过执行以下操作从我的 t.test 打印我的 p 值时:

ttest_bb[3]

它返回完整的 p 值。我怎样才能使它只打印前两个整数?即.03而不是.034587297

标签: r

解决方案


t.test 的输出是一个列表。如果您仅用于[获取 p 值,则返回的是一个包含一个元素的列表。如果[[要将其视为向量,则要使用 t.test 返回的列表中的位置获取包含的元素。

> ttest_bb <- t.test(rnorm(20), rnorm(20))
> ttest_bb

    Welch Two Sample t-test

data:  rnorm(20) and rnorm(20)
t = -2.5027, df = 37.82, p-value = 0.01677
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -1.4193002 -0.1498456
sample estimates:
 mean of x  mean of y 
-0.3727489  0.4118240 

> # Notice that what is returned when subsetting like this is
> # a list with the name p.value
> ttest_bb[3]
$`p.value`
[1] 0.01676605
> # If we use the double parens then it extracts just the vector contained
> ttest_bb[[3]]
[1] 0.01676605
> # What you're seeing is this:
> round(ttest_bb[3])
Error in round(ttest_bb[3]) : 
  non-numeric argument to mathematical function

> # If you use double parens you can use that value
> round(ttest_bb[[3]],2)
[1] 0.02
> # I prefer using the named argument to make it more clear what you're grabbing
> ttest_bb$p.value
[1] 0.01676605
> round(ttest_bb$p.value, 2)
[1] 0.02

推荐阅读