0% found this document useful (0 votes)
51 views2 pages

R Cheat Sheet for Data Analysis

1. The document provides examples of using functions from the mosaic package to conduct numerical summaries, linear regression, general graphics, hypothesis testing, and working with data. 2. It shows how to create a contingency table and calculate group means. It also demonstrates plotting a scatterplot with regression lines conditioned on a grouping variable. 3. The examples illustrate how to investigate whether an explanatory variable can be dropped from a linear model and calculate percentiles from a theoretical distribution.

Uploaded by

Sieben Doppelt
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)
51 views2 pages

R Cheat Sheet for Data Analysis

1. The document provides examples of using functions from the mosaic package to conduct numerical summaries, linear regression, general graphics, hypothesis testing, and working with data. 2. It shows how to create a contingency table and calculate group means. It also demonstrates plotting a scatterplot with regression lines conditioned on a grouping variable. 3. The examples illustrate how to investigate whether an explanatory variable can be dropped from a linear model and calculate percentiles from a theoretical distribution.

Uploaded by

Sieben Doppelt
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

R-cheatsheet 1

Help Numerical summaries Linear regression


These functions from the mosaic-package uses a for-
? mula syntax. model <- lm() # fit linear model
?? summary(model) # model fit summary
example() favstats() # min/max, median, etc. coef(model) # estimated parameters
apropos() tally() # tabulate data confint(model) # CI for estimates
[Link]() mean() anova(model) # F-tests, etc.
median() drop1(model)
sd() # standard deviation rstudent(model) # Studentized residuals
cor() # correlation fitted(model) # fitted values
Packages plotModel(model)# plot regression lines
In order to use functionalities from a certain package,
we need to first install and then load the package: General graphics model <- glm() # generalized linear model

# install package (do once):


gf_boxplot()
[Link]("") Data
gf_point() # scatter plot
gf_histogram()
# load package (do once in every script):
gf_bar() # bar graph # Load data:
require(); library()
[Link](); [Link](); [Link]()
mplot(HELPrct)# different plots
splom() # matrix of scatter plots # Data information
Formula syntax nrow(); ncol() # data dimensions
Most of the functions that we need for this course uses head() # extract first part of data
a formula syntax: Distributions tail() # extract last part of data
colnames() # column names
goal(y ~ x | z, data = mydata, ...) rownames() # row names
plotDist() # plot theoretical distribution
summary()
where goal may be a function for plotting, calculat- pdist() # find prob. from percentile
ing numerical summaries or making inference. qdist() # find percentile from prob.
# Alter/create data:
For plots: subset() # subset data by condition
Hypothesis tests factor() # create grouping variable
• y is y-axis variable relevel() # change reference level
cut() # cut numeric into intervals
• x is x-axis variable [Link]() # t-test round() # rounding numbers
[Link]() # binomial (exact) test c() # concatenate numerics
• z a conditioning variable (separate panels). [Link]() # approximate test seq() # create sequence
[Link]() # Fisher's exact test with()
For other things:
[Link]() # correlation test aggregate()
‘y ~ x | z’ can usually be read ‘y is modeled by (or [Link]() # chi-square test [Link]() # sum table entries
depends on) x differently for each z’.
Examples 2

The following are examples of how some of the func- # Make a scatterplot of 'pcs' versus 'age' # Investigate whether we may drop 'age' as an
tions work (based on mosaic’s built-in data set, # coloured by 'sex' and add regression lines: # explanotary variable for 'pcs', when
HELPrct). We assume mosaic is already loaded. In gf_point(pcs~age, col = ~sex, data = HELPrct) %>% # 'substance' is in the linear model too:
some chunks only the code and not the output is gf_lm() %>% mod1 <- lm(pcs ~ age + substance, data = HELPrct)
shown (to see the output, copy-paste the code chunk gf_labs(x = "Age", mod2 <- lm(pcs ~ substance, data = HELPrct)
of interest into your console). y = "Physical score", anova(mod1, mod2)
title = "My first scatter plot")
# Create a contingency table for 'sex' and Analysis of Variance Table
# 'substance':
tally(sex ~ substance, data = HELPrct) My first scatter plot Model 1: pcs ~ age + substance
Model 2: pcs ~ substance

Physical score
substance 60 sex [Link] RSS Df Sum of Sq F Pr(>F)
sex alcohol cocaine heroin female 1 449 47517
40
female 36 41 30 male 2 450 50139 -1 -2623 24.8 9.2e-07
male 141 111 94 20

20 30 40 50 60
Illustration of how the functions pdist and qdist
# Calculate mean 'age' for men and women: Age works:
mean(age ~ sex, data = HELPrct) # Calculate the 95th percentile for the
Note: gf point creates the scatter plot, gf lm adds
regression lines and gf labs adds a title and change # standard normal distribution (i.e., mean = 0
female male # and standard deviation = 1):
36.25 35.47 axis labels.
qdist("norm", p = 0.95, mean = 0, sd = 1)

# 'favstats' can be used to retrieve different # Use an exact binomial test to test whether [1] 1.645
# summaries of the data (here for 'age' # the proportion of women is 50 %:
0.4
# separated by sex) : [Link](~sex, p = 0.5, data = HELPrct)
favstats(age ~ sex, data = HELPrct) 0.3 probability

density
0.2 A: 0.950
sex min Q1 median Q3 max mean sd B: 0.050
1 female 21 31 35 40.5 58 36.25 7.585 # Use a t-test to test whether the mean age of 0.1

2 male 19 30 35 40.0 60 35.47 7.750 # men and women are the same:
0.0
n missing [Link](age ~ sex, data = HELPrct) −2 0 2
1 107 0 # Calculate the probability of getting a value
2 346 0 # less than -1.5 for the standard normal
# Use a chi-square test to test for # distribution:
# Boxplot of 'age' for each substance with # independence between 'homeless' and 'sex': pdist("norm", q = -1.5, mean = 0, sd = 1)
# different panels for men and women: tab <- tally(homeless ~ sex, data = HELPrct)
gf_boxplot(age ~ substance | sex, data = HELPrct) [1] 0.06681
[Link](tab)
0.4
female male
60
# Use an approximate test to see whether the
0.3 probability
# proportion of homeless is the same for men

density
50
# and women: 0.2 A: 0.067
age

40 B: 0.933
[Link](homeless ~ sex, data = HELPrct) 0.1
30

20 0.0
alcohol cocaine heroin alcohol cocaine heroin −2 0 2
substance

Common questions

Powered by AI

The prop.test is an approximate test used for comparing proportions between groups and determining if there is a significant difference . It assumes large sample sizes for valid results. In contrast, the chisq.test evaluates if there is a significant association between categorical variables by comparing observed frequencies to expected frequencies under independence . While prop.test examines differences in proportions, chisq.test assesses overall independence, with differences mainly in assumptions, applicability, and interpretation of results.

Together, gf_point, gf_lm, and gf_labs enhance data visualization by enabling layered plot construction in R. gf_point creates scatter plots, which display data points. gf_lm adds regression lines to these plots, revealing linear relationships between variables. gf_labs is used to add titles and axis labels, providing context and clarity. The combined use of these allows for detailed and informative visual analysis of data, showing trends and supporting understanding of data relationships, thus improving interpretability of the graphical outputs .

One might choose a chi-square test over Fisher's exact test when dealing with large sample sizes, as it is computationally less intensive and sufficiently accurate in such contexts . The chi-square test approximates the distribution better than the exact calculations required in Fisher's test, making it more practical for evaluating independence between categories in large contingency tables. However, if the sample size is small or if the data includes low frequency counts, Fisher's exact test would be more reliable. The choice depends on trade-offs between computational efficiency and test assumptions .

read.csv and read.delim are foundational functions for importing data into R, each optimized for specific file types. read.csv is ideal for comma-separated values, commonly used for large data sets because it handles them quickly and efficiently . read.delim is suited for tab-delimited files, useful when data is structured this way. Both functions simplify data preparation by automatically reading and structuring data frames. However, their limitations include lack of support for complicated file encodings, requiring manual specification of options for different delimiters, and handling missing data .

The lm() function in R is used to fit linear models, which is central to linear regression analysis. The purpose is to understand relationships between a response variable and one or more predictor variables. When using lm(), one specifies a formula where a dependent variable is modeled as a function of independent variables, i.e., Y ~ X1 + X2 + ... + Xn. This function estimates model coefficients that best predict the dependent variable from the independent variables. After fitting, it allows users to perform diagnostics, display coefficients, and make predictions .

In R, the formula syntax Y~X|Z involves modeling where 'Y' is dependent on 'X' with an additional condition set by 'Z'. When used in regression or plotting, 'Y' is calculated or plotted against 'X' with adjustments or separate panels for each level or condition of 'Z'. In regression analysis, this allows for considering the interaction or different effects of 'X' on 'Y' within strata defined by 'Z'. This is useful in understanding how relationships vary across different subgroups .

favstats is significant in R for its concise and comprehensive data summaries during exploratory data analysis (EDA). It computes statistics such as mean, median, standard deviation, and quantiles that provide immediate insights into the distribution and central tendency of variables. This facilitates understanding of data shape, variability, and outliers, which are critical in formulating hypotheses and determining further analytical steps. It simplifies EDA by combining various summary statistics into single, interpretable outputs .

The binom.test is best suited for scenarios where the interest lies in testing the success probability of binary outcomes or proportions, especially small sample sizes where exact statistics are needed. It is chosen over approximate tests, like prop.test, because it doesn't rely on large sample assumptions and directly evaluates the probability of observing the data under the binomial distribution. Its assumptions include independent trials, fixed number of trials, and each trial resulting in a binary outcome .

ANOVA can determine the significance of explanatory variables in a regression model by comparing the fit of nested models. By fitting models with and without the variables of interest, ANOVA tests whether removing a variable significantly reduces the model's explanatory power. This involves comparing the residual sum of squares (RSS) between models. A significant F-statistic indicates that the variable contributes explanatory power, justifying its inclusion. This helps in model selection by identifying which variables significantly affect the response variable .

The mosaic package streamlines data manipulation and analysis in R by providing a suite of functions optimized for teaching and performing statistical operations. It emphasizes formula syntax, making data operations consistent and expressive, especially for users familiar with mathematical notation. Functions such as favstats and tally offer simple yet powerful tools for summarizing and tabulating data. Additionally, graphics functions like gf_point and gf_boxplot support data visualization. Mosaic's design focuses on reducing coding complexity while encouraging statistical exploration and learning .

You might also like