Performing T-Tests in R — Stats with R (2024)

T-test-Markdown.knit

',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m

o.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);

'); $(tabs[0]).before(tabContent); // build the tabset var activeTab = 0; tabs.each(function(i) { // get the tab div var tab = $(tabs[i]); // get the id then sanitize it for use with bootstrap tabs var id = tab.attr('id'); // see if this is marked as the active tab if (tab.hasClass('active')) activeTab = i; // remove any table of contents entries associated with // this ID (since we'll be removing the heading element) $("div#" + tocID + " li a[href='#" + id + "']").parent().remove(); // sanitize the id for use with bootstrap tabs id = id.replace(/[.\/?&!#<>]/g, '').replace(/\s/g, '_'); tab.attr('id', id); // get the heading element within it, grab it's text, then remove it var heading = tab.find('h' + tabLevel + ':first'); var headingText = heading.html(); heading.remove(); // build and append the tab list item var a = $('' + headingText + ''); a.attr('href', '#' + id); a.attr('aria-controls', id); var li = $('

  • '); li.append(a); tabList.append(li); // set it's attributes tab.attr('role', 'tabpanel'); tab.addClass('tab-pane'); tab.addClass('tabbed-pane'); if (fade) tab.addClass('fade'); // move it into the tab content div tab.detach().appendTo(tabContent); }); // set active tab $(tabList.children('li')[activeTab]).addClass('active'); var active = $(tabContent.children('div.section')[activeTab]); active.addClass('active'); if (fade) active.addClass('in'); if (tabset.hasClass("tabset-sticky")) tabset.rmarkdownStickyTabs(); } // convert section divs with the .tabset class to tabsets var tabsets = $("div.section.tabset"); tabsets.each(function(i) { buildTabset($(tabsets[i])); });};

    To begin, I am going to set up the data.The fake variables created will represent the cost of Eggs and Milk atvarious grocery stores. The set.seed() function will allow the rnorm()functions to return the same values for you as they have for me. Thernorm() functions will each generate 10 values from a normaldistribution with each Eggs having a population mean of 5 and Milkhaving a population mean of 4. The default standard deviation is 1. Ifyou want to use your own data simply use the c() to create 1 or 2vectors for use below, you can use the example variable as areference.

    # Setting up the dataset.seed(123)Eggs = rnorm(10, mean = 5)Milk = rnorm(10, mean = 4)example = c(1,2,3,4,5,6,7,8,9)

    We first want to know if it is reasonable to believe that the datawe have is normally distributed. Many people would use a histogram orstatistical test for this, while both can be valid, a preferred methodis using what is called a QQ-plot. A QQ-plot compares the density ofyour variable to the density of an ideal standard normal distribution todetermine if they are similar. I am introducing a function thatstandardizes the distribution (or turns it into z-scores) to match themean and standard deviation of the comparison distribution. What weactually care about is that the points on the graphs fall near the lineuniformly, more tips for interpreting QQ-plots can be found starting onpg.46 of my book here https://www.statswithr.com/neural-networks-with-keras-in-r-a-quickstart-guide.The plots below are representative of what you can expect a normallydistributed variable to look like with a small sample size. With asample size less than 30, points generally falling close to the line issufficient. If the data is determined to not be normal, you will need toeither transform the data or use a non-parametric version of the t-testwhich comes at a loss of statistical power (ability to find statisticalsignificance).

    # Transforms the variable to have mean 0 and sd 1standardize <- function(x){return((x-mean(x))/sd(x))}# qqnorm makes the plot, abline draws the lineqqnorm(standardize(Eggs), main = "QQ Plot of Eggs")abline(0,1)

    Performing T-Tests in R — Stats with R (1)

    # qqnorm makes the plot, abline draws the lineqqnorm(standardize(Milk), main = "QQ Plot of Milk")abline(0,1)

    Performing T-Tests in R — Stats with R (2)

    Lets start with the one sample t-test, where we test the hypothesisthat the population mean of Eggs is 4. We know that the population meanis actually 5 (because we set it that way), so we expect to reject thenull hypothesis assuming our sample size is sufficiently large. Below weare able to reject the null hypothesis and determine that the populationmean is likely not 4. Notice that the degrees of freedom is n-1, andthat the confidence interval does not include 4.

    # One sample t-testt.test(Eggs, mu = 4)
    ## ## One Sample t-test## ## data: Eggs## t = 3.5629, df = 9, p-value = 0.006091## alternative hypothesis: true mean is not equal to 4## 95 percent confidence interval:## 4.392330 5.756922## sample estimates:## mean of x ## 5.074626

    Before we continue with two sample t-tests, we will want to get anidea if the variances are equal. With this generated data, we know thatthey are, but we should not assume that. var.test() can give us an ideaif that assumption is met. If this test is not statisticallysignificant, the equality of variance can be assumed. If the variancesare found to likely not be equal, we can still perform t-tests, we willsimply need to assume unequal variance in the t.test() function.

    var.test(Eggs, Milk)
    ## ## F test to compare two variances## ## data: Eggs and Milk## F = 0.8442, num df = 9, denom df = 9, p-value = 0.8049## alternative hypothesis: true ratio of variances is not equal to 1## 95 percent confidence interval:## 0.2096867 3.3987337## sample estimates:## ratio of variances ## 0.8441974

    Now, let’s perform a two sample t-test; the default setting assumesunequal variance, which means the degrees of freedom are reducedslightly (17.872 instead of 18). Use this if the prior test isstatistically significant with the p-value < 0.05. Note that doingthis makes it slightly more difficult to find an effect. This test wasnot statistically significant with a p-value of 0.06799, which is ofcourse above 0.05. We fail to reject the null hypothesis that thepopulation means between Eggs and Milk are equivalent.

    # basic t-test assuming unequal variancet.test(Eggs,Milk)
    ## ## Welch Two Sample t-test## ## data: Eggs and Milk## t = 1.9426, df = 17.872, p-value = 0.06799## alternative hypothesis: true difference in means is not equal to 0## 95 percent confidence interval:## -0.07104883 1.80305620## sample estimates:## mean of x mean of y ## 5.074626 4.208622

    Now, when we assume equal variance our degrees of freedom isexactly 18 or n-2. We once again fail to reject the null hypothesis;however, you will notice that the p-value here is slightly lower thanthe previous p-value by 0.00012. This means that we were just a littlecloser to rejecting the null hypothesis, which is related to the testbeing slightly more powerful in the statistical sense.

    # assume equal variancet.test(Eggs, Milk, var.equal = TRUE)
    ## ## Two Sample t-test## ## data: Eggs and Milk## t = 1.9426, df = 18, p-value = 0.06787## alternative hypothesis: true difference in means is not equal to 0## 95 percent confidence interval:## -0.07056945 1.80257682## sample estimates:## mean of x mean of y ## 5.074626 4.208622

    Until now we have been doing what are called two-tailed testsmeaning that we are simply testing if the population means of Milk andEggs are different in some way. If we want to test the hypothesis thatthe population mean of Eggs is greater than the population mean of Milkwe have to change the “alternative” argument of the function to greater.Note that the order of Eggs and Milk matters in this situation; if Milkwere first in the function below, we would be testing the oppositehypothesis. The t-test is finally significant with the p-value <0.05. Directional hypothesis tests have more power to find effects, butit is important that we have a prior hypothesis to justify the use of adirectional hypothesis test. Depending on the application, it is morecommon to use two-tailed hypothesis tests, as one-tailed tests can belooked upon negatively.

    # Eggs greater than Milkt.test(Eggs, Milk, alternative = "greater")
    ## ## Welch Two Sample t-test## ## data: Eggs and Milk## t = 1.9426, df = 17.872, p-value = 0.03399## alternative hypothesis: true difference in means is greater than 0## 95 percent confidence interval:## 0.0926739 Inf## sample estimates:## mean of x mean of y ## 5.074626 4.208622

    Now, we will test the opposite hypothesis. As you may have guessed,this is nowhere near significant, with the p-value being equal to 1minus the previous p-value. If you get a large p-value like this, it isworth checking if you specified the correct direction in yourfunction.

    # Eggs less than Milkt.test(Eggs, Milk, alternative = "less")
    ## ## Welch Two Sample t-test## ## data: Eggs and Milk## t = 1.9426, df = 17.872, p-value = 0.966## alternative hypothesis: true difference in means is less than 0## 95 percent confidence interval:## -Inf 1.639333## sample estimates:## mean of x mean of y ## 5.074626 4.208622

    Finally, we will perform a paired samples t-test. The two variableswe have been using are not appropriate for this type of analysis, so Iam creating a variable for the milk price next week that depends on thecurrent milk price. Paired samples t-tests are meant to be performed ondata that are not independent samples. A common form of this is a testretest situation where the same individuals are tested twice, before andafter some manipulation. A regular t-test is inappropriate because thesamples are not independent, so we use a paired sample t-test thataccounts for the same individuals being tested twice. In this example,the milk price is being observed and then we are waiting a week andre-observing them. The p-value < 0.05, so we can say that there is astatistically significant difference between weeks, and the 95%confidence interval for the increase ranges from 0.39 and 1.76 for thepopulation means.

    # New variable milk next weekset.seed(123)Milk_Next_Week <- Milk + rnorm(10, mean = 1)# paired t-testt.test(Milk_Next_Week, Milk, paired = TRUE)
    ## ## Paired t-test## ## data: Milk_Next_Week and Milk## t = 3.5629, df = 9, p-value = 0.006091## alternative hypothesis: true mean difference is not equal to 0## 95 percent confidence interval:## 0.3923296 1.7569217## sample estimates:## mean difference ## 1.074626
  • Michael Harris

    Performing T-Tests in R — Stats with R (2024)

    References

    Top Articles
    Latest Posts
    Article information

    Author: Sen. Ignacio Ratke

    Last Updated:

    Views: 5816

    Rating: 4.6 / 5 (56 voted)

    Reviews: 95% of readers found this page helpful

    Author information

    Name: Sen. Ignacio Ratke

    Birthday: 1999-05-27

    Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

    Phone: +2585395768220

    Job: Lead Liaison

    Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

    Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.