Chia Shen Tsai
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: "Tutorial 9: Paired t-test" author: "Elizabeth A. Albright, PhD" output: rtf_document --- # Tutorial 9: Paired t-test ```{r libraries, include=F} library(moments) #package for skewness library(knitr) #package for making tables (kable) library(tidyverse) #multiple packages for data wrangling library(gt) # a package to make tables library(lubridate) # a package to manipulate dates ``` ```{r tutorial6} rm(list=ls()) #removing objects airquality.df<-read_csv("airquality.csv") #reading data airquality.df <- airquality.df %>% #making airquality data frame mutate(date=mdy(`Date Local`))%>% #making date variable glimpse() #looking at data ``` In this next chunk I am making a new data frame of paired data, so i can show you how to calculate a paired t-test. For each monitoring site (`Site Num`) i want two observed values, one observation on July 1, 2019, and one observation of December 31, 2019. I am doing this to make a paired data set for demonstration purposes. ```{r paired} az.paired.df<-airquality.df %>% # making a new dataframe named az.paired.df filter(`State Name`=="Arizona") %>% #filtering only Arizona by State Name filter(date =="2019-07-01"|date=="2019-12-31")%>% #filtering only two dates group_by(`Site Num`)%>% #im grouping by Site Num so i can count how many observations for each Site Num mutate(n=n())%>% #i'm using mutate to count # of observations for each Site Num. the function is n() filter(n==2)%>% #i'm filtering here on n for two observations glimpse() #i'm looking at the data ``` To make things easier, I'm selecting the variables of interest: `Site Num`, date, ozone. ```{r} az.paired.df<-az.paired.df%>% select(`Site Num`, date, ozone)%>% arrange(`Site Num`, date) head(az.paired.df) ``` We can run the paired t-test using the following chunk with the grouping variable date. ```{r} t.test(ozone ~ date, az.paired.df, alternative="greater", paired=T) ``` But now we need to test the assumption of the paired t-test--this is normally distributed population of differences. This is a little tricky because of how the data are structured with a grouping variable (long data!), but we can pivot the data to make it wide with the dplyr function pivot_wider(). ```{r} az.paired.wide.df<-az.paired.df%>% #making a new data frame in the wide format pivot_wider(names_from=date, values_from=ozone)%>% #making data wider by taking the names from date (2019-12-31 and 2019-07-01) and placing the values of the observations into those two columns glimpse() az.paired.wide.df ``` We now can use mutate() to calculate the difference between the two variables Our new wide data set should have three variables: (1) `Site Num`, `2019-12-31` and `2019-07-01`. And now we can calculate the difference in ozone levels (ppm) between the two dates. ```{r} az.paired.wide.df<-az.paired.wide.df%>% #Now I am taking the mutate(diff=`2019-07-01`-`2019-12-31`) #making a new variable using subtraction az.paired.wide.df #allows us to see the new data frame with the diff variable ``` Now we can check to see whether the differences are pulled from a normal distribution (with the Shapiro-Wilk test). ```{r} shapiro.test(az.paired.wide.df$diff) ``` Argh. Barely okay. Not great. Ugh. let's make a histogram of the differences. I'm not going to make it pretty. You should do that in your assignments, though = ). ```{r} ggplot(data=az.paired.wide.df, aes(x=diff))+ geom_histogram() ``` Yeah, looks to be positively skewed (you should calculate skewness). What could we do? You guessed it--we could log the data and take the difference of the logs. ```{r} az.paired.wide.df<-az.paired.wide.df%>% mutate(log.2019.07.01=log(`2019-07-01`), log.2019.12.31=log(`2019-12-31`), diff.in.log=log.2019.07.01-log.2019.12.31)%>% glimpse() ``` Now we can do a paired t-test on the differences in the logged data. ```{r} t.test(az.paired.wide.df$log.2019.07.01, az.paired.wide.df$log.2019.12.31, paired=TRUE, alternative="greater") ``` ```{r} exp(0.2874) exp(0.2238) ``` 1.33 is the estimate of the median of the individual ratios. Please see the Statistical Sleuth on page 74. In a randomized paired treatment study, this value exp(Z) represents a multiplicative treatment effect. Now let's calculate Shapiro Wilk on the differences of the logged values! ```{r} shapiro.test(az.paired.wide.df$diff.in.log) ``` ```{r} ggplot(data=az.paired.wide.df, aes(x=diff.in.log))+ geom_histogram() ``` Well crap--that really didn't help (and it looks like it made things worse (Shapiro Wilk has an even smaller p-value which means we reject the null that the sample (of the differences) was drawn from a normal distribution)). What else could we try?!?! How about a comparison test that does NOT assume normality of the population of differences? That's the non-parametric Wilcoxon signed rank test. The function is wilcox.test(). Use ?wilcox.test to see the argument. ```{r} non.parametric.paired <- wilcox.test(az.paired.wide.df$`2019-07-01`, az.paired.wide.df$`2019-12-31`, paired = TRUE, alternative="greater") non.parametric.paired ``` We report the V (701) and p-value (p<0.001) in the context of the hypotheses for the Wilcoxon signed rank test (see lecture notes). So, okay, let's summarize what we did: (1) a paired t-test comparing ozone on July 1, 2019 to December 31, 2019 to say something about the mean of the differences. the differences marginally passed the Shapiro-Wilk test. Paired t-test isn't very sensitive to violations of normality assumption, so may be okay. (2) a paired t-test comparing the log of ozone on July 1, 2019 to log ozone on December 31, 2019 to say something about the mean of the differences in log ozone. Differences in log ozone levels did not pass Shapiro Wilk test--I would report, but put less weight behind this test than (1). (3) ran a non-parametric Wilcoxon signed rank test. No assumption of normality needed. Conclusion is broader those (a location shift in distribution).

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully