Hamada Al
Hamada Al

Reputation: 111

Estimation of Differences Between Means of Two Paired Samples using R

I am at the beginning of the study of the language R-programming,

And I try to write my own function to constructs the confidence interval Estimation of Differences Between Means of Two Paired Samples.

This my code

My.Function <- function(X1,X2,con.int) {
    X1bar = sum(X1)/n
    X2bar = sum(X2)/n
    XD = X2-X1
    XDbar = sum(X2-X1)/n
    n = length(X1)
    Sd = sqrt((sum((XD-XDbar)^2))/(n-1))
    Alpha = 1 - con.int
    T = qt(Alpha/2, n-1)
    Lower.B = (X2bar - X1bar) - T*Sd/sqrt(n)
    Uper.B = (X2bar - X1bar) + T*Sd/sqrt(n)
    print(c(Lower.B,"X2bar - X1bar",Uper.B))
}

I need to display the result and write clarifications with it, but I could not .

Thanks for help

Upvotes: 0

Views: 127

Answers (1)

wmay
wmay

Reputation: 234

You're not too far off.

R runs your code in the order you write it. So you have to create n before you can use it in calculations.

My.Function=function(X1,X2,con.int){
  n = length(X1) # this comes first!!
  X1bar=sum(X1)/n
  X2bar=sum(X2)/n
  XD = X2-X1
  XDbar=sum(X2-X1)/n
  Sd =sqrt((sum((XD-XDbar)^2))/(n-1))
  Alpha = 1- con.int
  T = abs(qt(Alpha/2, n-1))
  Lower.B = (X2bar - X1bar)- T*Sd/sqrt(n)
  Uper.B = (X2bar - X1bar)+ T*Sd/sqrt(n)
  print(c(Lower.B,"X2bar - X1bar",Uper.B))
}

I also took the absolute value of the T-score so that your upper and lower bounds don't get mixed up when qt() returns a negative number.

You might also like the cat function for printing the results. https://stat.ethz.ch/R-manual/R-devel/library/base/html/cat.html

Upvotes: 1

Related Questions