Home > database >  Vectorize the Mean Value in t.test(x, m = hu) Function Using R
Vectorize the Mean Value in t.test(x, m = hu) Function Using R

Time:04-22

I have a vector in which I want to vectorize a set of hypothesise mean values.

This is what I mean, if I have the following:

n <- c(10,15,20,25,30,40,50,100,250) # Sample size 
m <- 100        # Mean of the generated normal variable
vv <- 25        # variance of the generated normal variable
s <- sqrt(vv)
x <- rnorm(n, m, s)
hu  <-  c(85, 87.5, 90, 92.5, 95, 97.5, 100, 102.5, 105, 107.5, 110, 112.5, 115) # Hypothesized value of Mean of the generated normal variable
t.test(x, m = 115)$p.value  # here I chose a scalar hypothesised mean value
# [1] 2.080525e-07    

But when m is a vector of c(85, 87.5, 90, 92.5, 95, 97.5, 100, 102.5, 105, 107.5, 110, 112.5, 115)

t.test(x, m = hu)$p.value  # here I chose a vector of hypothesised mean value
# Error in t.test.default(x, m = hu) : 'mu' must be a single number 

I got the above error message.

What I Want

I want to run t.test(x, m = hu)$p.value where hu is a vector of c(85, 87.5, 90, 92.5, 95, 97.5, 100, 102.5, 105, 107.5, 110, 112.5, 115) such that I will have a vector output

CodePudding user response:

We can use a loop as mu in ?t.test takes a single value as input

mu - a number indicating the true value of the mean (or difference in means if you are performing a two sample test).

sapply(hu, function(u) t.test(x, mu = u)$p.value)

-output

[1] 1.053213e-05 3.227459e-05 1.161963e-04 5.126058e-04 2.903163e-03 2.146785e-02 1.777964e-01 9.192412e-01 2.403805e-01 2.966405e-02 3.873822e-03 6.563008e-04
[13] 1.436296e-04
  • Related