CI_t <- function (x, ci = 0.95)
{
  `%>%` <- magrittr::`%>%`
  Margin_Error <- qt(ci + (1 - ci)/2, df = length(x) - 1) * sd(x)/sqrt(length(x))
  df_out <- data.frame( sample_size=length(x), Mean=mean(x), sd=sd(x),
                        Margin_Error=Margin_Error,
                        'CI lower limit'=(mean(x) - Margin_Error),
                        'CI Upper limit'=(mean(x) + Margin_Error)) %>%
    tidyr::pivot_longer(names_to = "Measurements", values_to ="values", 1:6 )
  return(df_out)
}


CI_z <- function (x, ci = 0.95)
{
  `%>%` <- magrittr::`%>%`
  standard_deviation <- sd(x)
  sample_size <- length(x)
  Margin_Error <- abs(qnorm((1-ci)/2))* standard_deviation/sqrt(sample_size)
  df_out <- data.frame( sample_size=length(x), Mean=mean(x), sd=sd(x),
                        Margin_Error=Margin_Error,
                        'CI lower limit'=(mean(x) - Margin_Error),
                        'CI Upper limit'=(mean(x) + Margin_Error)) %>%
    tidyr::pivot_longer(names_to = "Measurements", values_to ="values", 1:6 )
  return(df_out)
}



dat <- c(15.4,9.21,4.2,7.5,12.2,18.3,17.3,
         14.3,14.02, 20, 12.3, 14.1, 17.3, 15.4,
         12.2,11.4, 9.1,18,14.43,17,15.1,13.4,
         15.3, 12.2,13.3)
CI_t(dat, ci = 0.95)
## # A tibble: 6 x 2
##   Measurements   values
##   <chr>           <dbl>
## 1 sample_size     25   
## 2 Mean            13.7 
## 3 sd               3.60
## 4 Margin_Error     1.49
## 5 CI.lower.limit  12.2 
## 6 CI.Upper.limit  15.2
data.frame(dat)
##      dat
## 1  15.40
## 2   9.21
## 3   4.20
## 4   7.50
## 5  12.20
## 6  18.30
## 7  17.30
## 8  14.30
## 9  14.02
## 10 20.00
## 11 12.30
## 12 14.10
## 13 17.30
## 14 15.40
## 15 12.20
## 16 11.40
## 17  9.10
## 18 18.00
## 19 14.43
## 20 17.00
## 21 15.10
## 22 13.40
## 23 15.30
## 24 12.20
## 25 13.30
# Calculate the mean and standard error
l.model <- lm(dat ~ 1, data.frame(dat))

# Calculate the confidence interval
confint(l.model, level=0.95)
##                2.5 %   97.5 %
## (Intercept) 12.23044 15.20636
###  Since n < 30, we use t score with degrees of freedom_method_2
x_mean = mean(dat)
n = length(dat)
df = n - 1
S_sd = sd(dat)
ci = .95
ci_90 = x_mean + c(-1,1) * qt(ci+(1-ci)/2, df=df) * S_sd/sqrt(n)
ci_90
## [1] 12.23044 15.20636
t.test(dat)
## 
##  One Sample t-test
## 
## data:  dat
## t = 19.028, df = 24, p-value = 5.528e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  12.23044 15.20636
## sample estimates:
## mean of x 
##   13.7184
##########
#ref https://www.r-bloggers.com/2021/04/calculating-confidence-interval-in-r/