0% found this document useful (0 votes)
35 views5 pages

R Basics: Paired-Samples t Test Guide

Uploaded by

Viem Anh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views5 pages

R Basics: Paired-Samples t Test Guide

Uploaded by

Viem Anh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STA 2 - R LAB 2

Review on Basics of R (cont.) + Paired-Samples t Test


1. Objectives
 Basic graphical and tabular methods
 Editing graphs
 Paired-samples t-test
2. Basic tabular methods
Remember that before we apply a graphical or statistical method on a variable that is to be treated as a
categorical variable, we should be sure that it has been converted into a factor.
We can convert a character variable into a factor by the factor() function. For example,
 data1 <- [Link]("[Link]",header=TRUE,sep=",",quote="\"",
stringsAsFactors = FALSE) #Read data into R
 data1$am <- factor(data1$am,ordered=FALSE,levels=c(0,1),labels =
c("automatic","manual")) #Convert into categorical variable

Exercise 1:
a. Explain why the conversion of the data1$am variable is necessary in the above code.
b. Let’s check whether the data1$am variable has been converted into a factor correctly.
c. Go back to the code for importing a text file. What happens if we use stringAsFactors =
TRUE? Try this:
 data2 <- [Link]("[Link]",header=TRUE, sep=",",quote="\"",
stringsAsFactors=TRUE)

Now, let’s create a frequency table. We can try:


 [Link] <- table(data1$am)
 [Link]([Link])
 [Link]([Link])*100

To create a contingency table, use the following format of the table() function:
tableName <- table(row variable, column variable)

Exercise 2: Create a contingency table named gearVSam.table2 showing the relationship between
gear and am. Are you happy with the output? Let’s discuss how to improve it.

3. Basic graphical methods


3.1 Simple bar graph
Based on the frequency table produced previously, we can now produce a simple bar graph. The
following listing shows different ways to plot a bar graph.
 [Link] <- table(data1$am)
 barplot([Link])

1|P a ge
STA 2 - R LAB 2

 barplot([Link], main="Bar graph of Transmission", xlab="Types of


Transmission", ylab="Frequency",ylim=c(0,20))
 barplot([Link], main="Bar graph of Transmission", xlab="Types of
Transmission", ylab="Frequency", horiz=TRUE)
 barplot([Link], col="skyblue",main="Bar graph of Transmission ",
xlab=" Types of Transmission ", ylab="Frequency")

3.2 Clustered bar graph


Let’s type in the following code:
 [Link]<-table(data1$am,data1$gear)
 [Link]
 barplot([Link], beside=TRUE)
 barplot([Link], col=c("red", "yellow"),
beside=TRUE,ylim=c(0,20))

Exercise 3: For the above clustered bar graph


a. Add a title for the graph and labels for the two axes.
b. Use different colors for the bars
c. Convert gear variable to a factor before producing a contingency table and clustered bar graph
and observe the difference.
3.3 Stacked bar graph
The code below will produce a stacked bar graph
 barplot([Link],col=c("red","yellow"))
We can use the spineplot() function to produce a spine plot, a generalized version of the stacked bar
graph. Let’s observe how the spine plot differs from the previous stacked bar graph.
 spineplot([Link], col=c("blue", "green", "pink"))

3.4 Stem and leaf display


 mpg <- data1$mpg
 stem(mpg)

3.5 Histogram
 hist(mpg)
 hist(mpg,breaks=5,col="red")
 hist(mpg, freq=FALSE, breaks=5,col="red")

3.6 Boxplot
The following command is to work with boxplot (for numerical data):
 boxplot(data1$mpg)
 [Link](data1$mpg)
 boxplot(data1$mpg ~ data1$gear)

2|P a ge
STA 2 - R LAB 2

4. Editing graphs
4.1 Adding title and axis labels
The function title() adds title and axis labels to a graph. The general format is:
title(main="my title", sub="my sub-title", xlab="x-axis label", ylab="y-
axis label")

The title() function works with the currently active graph.


4.2 Adding a box outside the graph
Use the box()function

5. Paired-samples t Test
We can use the following code to conduct a paired-samples t test to see if the population mean
difference is not zero:
[Link] (y1, y2, paired=TRUE, alternative = …,[Link]=0.95)

where y1 and y2 are numeric vectors for the two matched groups and [Link] argument allows us
to specify the confidence level of the reported CI.
Exercise 4. Load the [Link] dataset. The dataset contains scores of the first and final rounds
for a sample of 20 golfers who completed in PGA tournaments. Suppose you would like to determine
if the mean score for the first round of a PGA Tour event is significantly different than the mean score
for the fourth and final round. Use R to generate the test output. Use  = 0.1.
a) What is the mean difference between in scores for the two rounds? For which round is the
sample mean score lower?
b) What is the p-value? Was the mean score significantly different for the two rounds?
c) What is the 90% confidence interval estimate for the difference between two population
means? Does this CI support your conclusion in part (b) (Does the interval include 0)?
d) Remember that in practice we have to check assumptions for each test we perform. Is the data
distribution for the paired differences reasonably normal?
Note: To check the normality of a dataset, a histogram can be used (but a QQ plot is more useful). In
case of small sample size, however, it is better to use the stem and leaf display and the qq plot to check
if data is normally distributed. The R code for a qq plot is as follows.
 qqnorm(data)#Compare quantiles of our data with theoretical normal
quantiles
 qqline(data)# Add a line to a normal quantile-quantile plot passing
through the first and third quartiles

If the data is normally distributed, the data points should fall in a straight line. Departures from the line
are indicative of a lack of normality.

3|P a ge
STA 2 - R LAB 2

The R output for this exercise is provided below. You are expected to write R code that produces the
same output:
Paired t-test

data: data3$First and data3$Final


t = -1.416, df = 19, p-value = 0.173
alternative hypothesis: true difference in means is not equal to 0
90 percent confidence interval:
-2.3322058 0.2322058
sample estimates:
mean of the differences
-1.05

Stem and Leaf Display of Golf Score Differences


The decimal point is 1 digit(s) to the right of the |

-0 | 7765
-0 | 43221
0 | 00111112234

Note: If the assumption of normality is violated, the t test may provide misleading results (you should
refer to the practical guidelines regarding how to use one-sample t-test in the Probability and Statistics
course). In such cases, we should use a nonparametric test (to be taught later in this course).
Exercise 5. Load the [Link] dataset. In early 2009, the economy was experiencing a
recession. The dataset contains data price per share of stock for a sample of 15 companies on January 1
and April 30 (The Wall Street Journal, May 1, 2009).

4|P a ge
STA 2 - R LAB 2

a. What is the change in the mean price per share of stock over the four-month period?
b. Provide a 90% confidence interval estimate of the change in the mean price per share of stock.
Interprete the results.
c. How was the recession affecting the stock market? Use  = .1
The R output for this exercise is provided below. You are expected to write R code that produces the
same output:

Paired t-test

data: data4$Jan and data4$Apr


t = 2.0043, df = 14, p-value = 0.06478
alternative hypothesis: true difference in means is not equal to 0
90 percent confidence interval:
0.2970457 4.6029543
sample estimates:
mean of the differences
2.45
Stem and Leaf Display of Price Changes
The decimal point is 1 digit(s) to the right of the |

-0 | 432211
0 | 12344
0 | 778
1 | 2

5|P a ge

Common questions

Powered by AI

Using the `box()` function enhances the visual clarity of a plot by adding a border around the plot area, which can help delineate it clearly from other elements or formatting aspects in complex data visualizations. It provides a defined boundary that can make the graphical components stand out more distinctly, aiding in focus and preventing visual distractions. Additionally, it can help secure axis labels and other annotations, ensuring they're visually framed within the plot's context, thereby enhancing the overall interpretability of dense or intricate plots .

Converting a character variable into a categorical variable using the `factor()` function in R is essential for statistical analysis that involves categorical data, as it explicitly specifies the variable's possible values and their respective factors. This conversion ensures that functions in R that are designed to handle categorical variables operate correctly. For instance, graphical and tabular methods that summarize categorical data rely on this conversion to produce accurate plots and tables. Without converting characters to factors, statistical methods might treat the data as continuous, leading to incorrect analyses. Additionally, factors are crucial for modeling since they allow the levels to be defined and ordered correctly, which affects the interpretation of results .

Switching the `stringsAsFactors` parameter from `TRUE` to `FALSE` in the `read.table()` function in R changes how character data is handled upon import. When `stringsAsFactors=TRUE`, R automatically converts character strings to factors, which might be desirable for categorical data. However, setting `stringsAsFactors=FALSE` prevents this conversion, and the data is read as character strings, preserving the original data type and avoiding unintended factor creation. This change is significant when dealing with large datasets or when further data manipulation is required without factor conversion, as it maintains flexibility in data handling by preventing premature categorization of data .

A stem-and-leaf display provides insights into the distribution, shape, and central tendencies of a dataset by representing numerical data in a format that retains actual data values. Unlike a histogram, which groups data into intervals and shows frequency as bars, a stem-and-leaf display shows individual data points, allowing for precise identification of data and its distribution pattern. This makes it particularly useful for small datasets where maintaining individual observations is essential for analysis. It succinctly illustrates data structure, highlighting patterns such as skewness, gaps, and clusters in the data, without losing the granular detail conveyed by raw numbers .

Assessing whether the data distribution of paired differences is reasonably normal is crucial when performing a paired-samples t-test in R because the validity of the t-test results depends on this assumption. The t-test assumes that the differences between paired observations are normally distributed. Significant departures from normality can lead to inaccurate estimates of the p-value and confidence intervals, potentially resulting in misleading conclusions about statistical significance. If the normality assumption is violated, especially with small samples, alternative non-parametric tests may be more appropriate. Verification of normality helps ensure that the test's critical values are appropriate and that the results are reliable .

When using histograms to check data normality, considerations should include the bin width or the number of bins chosen, as these can influence the perceived skewness or kurtosis, possibly misrepresenting the normality. Histograms provide a visual sense of data distribution but can be subjective based on how data is binned. A QQ plot is considered a more reliable method because it directly compares the quantiles of the sample data against the quantiles of a normal distribution, allowing for precise assessment of departures from normality. Deviations from a straight line in a QQ plot indicate deviations from normality, offering a clearer, less subjective analysis of normality .

Transforming the `gear` variable into a factor before creating a clustered bar graph affects the resulting plot by ensuring that the levels of the variable are explicitly defined and properly categorized, which leads to accurate representation of the categorical data. This transformation ensures that the bars in the graph are appropriately grouped and labeled according to the categorical levels of `gear`, rather than treating them as numerical values. This is especially recommended for enhancing the interpretability of the graph, as it maps each level of the factor correctly, facilitating accurate comparisons and insights into the relationships between categories .

A clustered bar graph displays groups of bars side by side for different categories, enabling easy comparison among these groups, whereas a stacked bar graph stacks the bars on top of each other for each category, which helps in understanding the whole composition rather than comparing individual parts. In a clustered bar graph, each sub-category is represented with its own bar, which facilitates a visual comparison of categories across groups, displaying distribution clearly when categories have similar values. Conversely, a stacked bar graph emphasizes the overall total for each primary category but limits comparative analysis between the sub-categories. These differences significantly affect data presentation by either highlighting individual category comparisons or showing the collective proportionality within categories .

If the p-value obtained from a paired-samples t-test is greater than the chosen significance level (for example, α = 0.05), it implies that there is insufficient evidence to reject the null hypothesis of no mean difference between the paired observations at the specified significance level. Practically, it means that any observed difference is not statistically significant, suggesting that the mean scores or measurements in the paired groups could be similar in the population. This outcome informs researchers that any observed difference may be due to random sampling variability rather than a true effect .

Creating labels and titles in plots using the `title()` function is important for effectively conveying information in graphical representations, as it provides context and clarity to the data being presented. Titles succinctly describe the main topic of the graph, while axis labels specify what each axis represents, ensuring that viewers can easily interpret the data without prior knowledge of the variables involved. These elements help communicate insights clearly, aiding in the comprehension of complex data by providing orientation and preventing misinterpretation of the plots' contents .

You might also like