Search code examples
rfunctionvectorstatisticst-test

How to extract the t-value as a bare number in R?


I've tried to unname() and use [[1]] to only extract the numeric value of t reported after a t.test() with no success.

I was wondering how I could extract the numeric value of t in a t.test command in R?

Here is an example:

t.value = unname(t.test(extra ~ group, var.equal = T, data = sleep))[[1]]

(gt = t.value / .2)  ## When you run this

#>         t   ## You see this extra `t` here, how to avoid getting this `t`?
#  -9.304067 

Solution

  • The unname should be after the extraction

    t.value <- unname(t.test(extra ~ group, var.equal = T, data = sleep)[[1]])
    t.value
    #[1] -1.860813
    

    Or other option is

    t.test(extra ~ group, var.equal = T, data = sleep)$statistic[["t"]]
    #[1] -1.860813
    

    Or we can use as.numeric


    In the OP's code, it is unnameing the list elements

    t.valueO <- t.test(extra ~ group, var.equal = T, data = sleep)
    names(t.valueO)
    #[1] "statistic"   "parameter"   "p.value"     "conf.int"    "estimate"    "null.value"  "alternative" "method"     
    #[9] "data.name"  
    
    names(unname(t.valueO))
    #NULL