Test <- function(xbar, mu0, s, n, alpha)
# xbar = sample mean
# mu0 = mean of population
# s = standard deviation of sample
# n = sample size
# alpha = alpha risk
{
t <- round(abs(qt(alpha/2, n-1)), digits = 3)
T <- (xbar-mu0)/s*sqrt(n)
print("critical value t(alpha) =")
print(t)
print("Teststatistic T =")
print(T)
if (abs(T) > t)
{
print("H0 rejected")
} else
{
print("H0 accepted")
}
}
If you use cat instead of print you can avoid the [1] that prints on each line, and it also allows you to print multiple things on a line without having to concatenate them yourself. You have to add end of line "\n" yourself.
I would be inclined to write your function like this:
Test <- function(xbar, mu0, s, n, alpha)
# xbar = sample mean
# mu0 = mean of population
# s = standard deviation of sample
# n = sample size
# alpha = alpha risk
{
t <- round(abs(qt(alpha/2, n-1)), digits = 3)
Tstat <- (xbar-mu0)/s*sqrt(n)
cat(
sprintf(
paste0(c("Critical values of t(alpha) = %s\n",
"Test statistics T = %s\n",
"%s\n\n",
collapse = "\n")),
t, # first %s
Tstat, # second %s
if (abs(Tstat) > t) "H0 rejected" else "H0 not rejected" # third %s
),
sep = ""
)
}
Test(57.1, 55, 1.4, 36, 0.01)
some notes:
In sprintf, you are building a string. The %s is a placeholder for a string to be added later. The values to be inserted are given as subsequent arguments. I often find this easier to read and understand than a lot of pasteing. (You may also want to see the glue package for similar functionality).
I changed your T variable to Tstat. T is, by default, a synonym for TRUE. You can overwrite it, but you might confuse yourself or others sometime in the future. I recommend avoiding it as an object name.
I changed your phrasing of H0 accepted to H0 not rejected. Hypothesis tests don't typically confirm a hypothesis. We either have enough evidence on hand to reject it, or we don't.
I strongly recommend the glue package, or the stringr wrappers, for building strings. Here's my adaptation of the prior response using the tidyverse:
library(tidyverse)
Test <- function(xbar, mu0, s, n, alpha)
# xbar = sample mean
# mu0 = mean of population
# s = standard deviation of sample
# n = sample size
# alpha = alpha risk
{
t <- round(abs(stats::qt(alpha/2, n-1)), digits = 3)
Tstat <- (xbar-mu0)/s*sqrt(n)
"Critical values of t(alpha) = {t}
Test statistics T = {Tstat}
{if (abs(Tstat) > t) 'H0 rejected' else 'H0 not rejected'}" %>%
str_glue() %>%
cat()
}