Search code examples
rstatisticst-test

How to apply t-test for groups by dates in R?


Sorry i am new in R and really need guidance for this: I have a dataset like this:

date        CVDadmissions 
2001.04.01   22
2001.04.02   26
2001.04.03   27
2002.04.01   22
2002.04.02   23
2002.04.03   25
2003.04.01   27
2003.04.02   28
2003.04.03   29
2003.04.04   30

I know how to compare the means group-wise but can someone please help me to put the code for how to apply t-test for comparison of admissions from 2001 to 2002?


Solution

  • In response to your question in the comments above.
    My approach is to convert the date column into an actual date object with the as.Date function. With that you can then subset/filter/select to the desired time periods (rows) to perform the t.test.

    df<-read.table(header = TRUE, text="date        CVDadmissions 
    2001.04.01   22
    2001.04.02   26
    2001.04.03   27
    2002.04.01   22
    2002.04.02   23
    2002.04.03   25
    2003.04.01   27
    2003.04.02   28
    2003.04.03   29
    2003.04.04   30")
    
    
    df$date<-as.Date(df$date, "%Y.%m.%d")
    
    t.test(CVDadmissions ~ format(date, "%Y"), data=df[df$date<as.Date("2003-01-01"),])
    
    #or 
    t.test(CVDadmissions ~ format(date, "%Y"), data=df[format(df$date, "%Y")=="2001" | format(df$date, "%Y")=="2002",])