如何用2个有效数字打印p值?

时间:2019-06-03 14:35:36

标签: r

当我通过以下方式从t.test打印我的p值时:

ttest_bb[3]

它返回完整的p值。我怎样才能使它只输出前两个整数?即用.03代替.034587297

1 个答案:

答案 0 :(得分:1)

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