data science
Table of contents
- Install and run packages, vectors, and data frames
- R vs. RStudio, code structure, and packages
- Data structures and objects
- Statistical concepts and vocabulary
- Mathematical operations and functions in R
- Data visualization and repetition
- Importing data into R
- Exploratory Data Analysis (EDA) and data manipulation
- Summary of R topics
1. Install and run packages, vectors, and data frames
1.1 R vs. RStudio
R is the programming language and environment for statistical computing and graphics, while RStudio is an integrated development environment (IDE) that provides a user-friendly interface for R 8.
1.2 Executable and unexecutable code
Executable lines of code are commands that R can process and execute, such as functions or assignments. Unexecutable lines include headings, visual separators, comments, and function arguments, which R ignores during execution 8.
- Comments: Lines starting with
#are comments, used for explanations and are not executed by R. - Functions: Predefined commands that perform specific tasks.
- Arguments: Parameters passed to functions to modify their behavior 8.
📝 Comments, which start with
#, are ignored by R, like# This is a comment8.
1.3 Packages
Packages are collections of R functions, data, and compiled code that extend R's capabilities 8.
1.4 Installing packages
Packages can be installed using a point-and-click interface within RStudio or via the command line.
📝 To install the
dplyrpackage, you would use the commandinstall.packages("dplyr")2.
1.5 Loading packages
Once installed, packages must be loaded into the current R session to be used.
library(package_name): Loads a package, making its functions available 2.require(package_name): Similar tolibrary(), but returns a boolean indicating success or failure 8.
1.6 Data structures
R supports various data structures, each with specific characteristics regarding dimensions, class, and attributes 8.
| Data Structure | Dimensions | Key Characteristics |
|---|---|---|
| Vectors | 1D | Homogeneous class, stores elements of the same type |
| Lists | 1D | Can store elements of different types |
| Matrices | 2D | Homogeneous class, rectangular shape |
| Data Frames | 2D | Heterogeneous columns, tabular format |
| Tibbles | 2D | Modern data frames with stricter rules |
| Arrays | nD | Homogeneous class, multi-dimensional |
1.7 Classes and attributes
Data structures have a class, which defines the type of data they hold (e.g., numeric, character, logical). They can also have attributes, such as names, dimensions, and class itself, which provide metadata 8 9.
- Numeric: Includes
doubles(default floating-point numbers) andintegers(whole numbers, often denoted withL, e.g.,1L). - Character: Stores text strings.
- Logical: Stores boolean values (
TRUE,FALSE, orT,F) 2. - Complex: Stores complex numbers.
- Factor: Used for categorical data, storing labels and their underlying integer representation 8.
1.8 Creating and manipulating vectors
Vectors are fundamental 1-dimensional data structures in R that store elements of the same class 8.
1.9 Vector creation
Vectors can be created using the c() function, which concatenates its arguments9.
c(element1, element2,...): Combines elements into a vector 2.
1.10 Vector classes
Vectors can be of numeric, character, or logical class8.
- Numeric:
1,2.5. - Integer:
1L,2L. - Logical:
TRUE,FALSE,T,F2.
1.11 Combining vectors
Vectors of the same class can be combined into a single vector.
new_vector <- c(vector1, vector2): Creates a new vector by combining existing ones 2.
1.12 Checking vector class
The is.TYPE() functions check if a vector belongs to a specific class 9.
is.numeric(vector_name): ReturnsTRUEif the vector is numeric,FALSEotherwise.is.character(vector_name): ReturnsTRUEif the vector is character,FALSEotherwise.is.logical(vector_name): ReturnsTRUEif the vector is logical,FALSEotherwise 2.
1.13 Vector length
The length() function returns the number of elements in a vector9.
length(vector_name): Outputs the number of elements 3.
1.14 Assignment and object inspection
Assignment operators are used to store values or results in named objects 7 9.
| Operator | Description |
|---|---|
| <- | Assigns the value on the right to the object on the left. |
| -> | Assigns the value on the left to the object on the right (less common). |
| = | Assigns the value on the right to the object on the left (can also be used for function arguments). |
1.15 Naming rules
Object names in R are case-sensitive and cannot start with a number or contain special characters like !, @, #, $, % 7.
1.16 Viewing object information
Several functions provide insights into the structure and content of objects.
head(object_name, n = number): Displays the firstnelements of an object (default is 6).tail(object_name, n = number): Displays the lastnelements of an object (default is 6) 2.view(object_name)orView(object_name): Opens the object in a new tab in RStudio for interactive viewing (capitalVis standard).- glimpse(objectname): Provides a concise summary of the object, including dimensions and data types.
class(object_name): Returns the class of the object 3 9.
1.17 Data frames
Data frames are 2-dimensional tabular data structures where columns can contain different data types, making them suitable for representing datasets 8.
1.18 Creating data frames
Data frames are created using the data.frame() function, with each argument representing a column9.
data.frame(column1_name = vector1, column2_name = vector2,...): Creates a data frame 2.
1.19 Accessing data frame elements
Data frames can be accessed using square brackets [] for rows and columns, or the $ operator for specific columns.
data_frame[row_index, column_index]: Selects a specific cell. Leaving a space blank selects all values for that dimension 6.data_frame$column_name: Selects an entire column as a vector 2 9.
1.20 Data frame dimensions and names
Functions exist to retrieve information about the structure of data frames.
names(object_name): Returns a vector of names for 1D objects; for 2D objects, it returns column names 2.colnames(object_name): Specifically returns the column names of 2D objects like data frames.length(object_name): For data frames, returns the number of columns.nrow(object_name): Returns the number of rows in a 2D object 3.ncol(object_name): Returns the number of columns in a 2D object 9.
1.21 Reading data into data frames
Data can be read from external files into data frames.
read.csv("file_name.csv", header = TRUE, sep = ","): Reads data from a CSV file.read.txt("file_name.txt", header = TRUE, sep = "\t"): Reads data from a tab-delimited text file.- read.delim("filename.txt",header=TRUE,sep="\t"): Another function for reading delimited text files 5.
1.22 Mathematical and statistical functions
R provides a suite of built-in functions for mathematical operations and statistical calculations 3 10.
| Function | Description |
|---|---|
| abs(value) | Calculates the absolute value. |
| ceiling(value) | Rounds a number up to the nearest integer. |
| floor(value) | Rounds a number down to the nearest integer. |
| round(value, digits = n) | Rounds a number to a specified number of decimal places. |
| factorial(value) | Computes the factorial of a non-negative integer. |
| log(value) | Calculates the natural logarithm. |
| log10(value) | Calculates the base-10 logarithm. |
| sqrt(value) | Computes the square root. |
| exp(value) | Calculates the exponential function (e^value). |
| mean(vector, na.rm = FALSE) | Calculates the average of vector elements. |
| median(vector, na.rm = FALSE) | Calculates the middle value of a sorted vector. |
| sd(vector, na.rm = FALSE) | Calculates the standard deviation. |
| IQR(vector, na.rm = FALSE) | Calculates the interquartile range. |
| range(vector, na.rm = FALSE) | Returns the minimum and maximum values. |
| quantile(vector, probs = X) | Calculates quantiles for specified probabilities. |
| min(vector, na.rm = FALSE) | Finds the minimum value in a vector. |
| max(vector, na.rm = FALSE) | Finds the maximum value in a vector. |
| summary(vector) | Provides a statistical summary (min, Q1, median, mean, Q3, max). |
| weighted.mean(vector, w = vector.of.weights) | Calculates the mean with specified weights. |
| table(vector, useNA = "no") | Creates a frequency table for a vector. |
| table(vector1, vector2, useNA = "no") | Creates a contingency table for two vectors. |
1.23 Z-score calculation
The z-score measures how many standard deviations a data point is from the mean11.
📝 To calculate the z-score for a variable named
my_data, you would use the formulaz.my_data <- (my_data - mean(my_data)) / sd(my_data)4.
1.24 Reproducing values
The rep() function is used to repeat elements or vectors a specified number of times.
1.25 Visualizations
R offers various functions for creating plots to visualize data 4 10 11.
1.26 Histograms
Histograms display the distribution of a single quantitative variable10 11.
hist(x = variable, col = "color",...): Creates a histogram 4.
1.27 Box plots
Box plots visualize the distribution of a quantitative variable, showing median, quartiles, and outliers11.
- Vertical box plot:
boxplot(variable, col = "color",...)4. - Horizontal box plot:
boxplot(variable, xlab = "...", horizontal = TRUE, col = "color",...)5.
2. R vs. RStudio, code structure, and packages
2.1 R and RStudio
R is the programming language itself, while RStudio is an Integrated Development Environment (IDE) that provides a user-friendly interface for writing and running R code. RStudio enhances the R experience by offering features like code editing, debugging, and visualization tools 14 15.
- R is the statistical programming language that performs computations and data analysis.
- RStudio is an IDE that simplifies the process of writing and executing R code, offering a more organized workflow 14 15.
2.2 R code structure
R code is organized into executable and non-executable lines, with specific conventions for comments, headings, and visual breaks to improve readability and maintainability 14 15.
- Executable lines of code are typically displayed in black or blue text, representing functions or commands that R will process.
- Non-executable lines of code, known as comments, are usually green and are ignored by R during execution.
- Comments are created using the
#symbol at the beginning or within a line. - Functions are predefined sets of instructions that simplify complex tasks within R.
- Functions are case-sensitive and enclosed in parentheses
(). - Arguments are the inputs provided to functions, separated by commas within the parentheses.
- Headings are used to structure R scripts, marked by at least one
#,=, or-at the beginning and four or more of these characters at the end (e.g.,# Heading 1 ####). - A single
#denotes a level one heading. ##denotes a level two heading.- Visual cuts are purely aesthetic lines (e.g.,
# ____________________________) used to create visual separation between different sections of code 14. NArepresents a missing value in R and can affect how functions handle data 15.
📝 Comments, which are ignored by R, are indicated by a
#symbol, like# This is a comment14.
2.3 Running R code
Executing R code involves specific commands and shortcuts, with indicators in the console to show the status of code execution 14 16.
- Running code is typically done by placing the cursor on the desired line and using a keyboard shortcut (e.g., Command + Enter on Mac).
- Highlighting multiple lines allows for the execution of several commands simultaneously.
- The
>symbol in the console indicates that R is ready to accept a new command. - The
+symbol in the console signifies that a command is incomplete and R is waiting for more input, often when a line of code is split across multiple lines 14. - Pressing the Escape key will return the console to the
>prompt 16.
2.4 File paths and shortcuts
R requires precise file paths to locate specific files, and RStudio offers specialized shortcuts to enhance coding efficiency 17 18.
- File paths act as an address, guiding R from the top level of a file system to a specific file.
- Folders within folders represent a file path (e.g., drive→folder→folder→file) 17.
- R-specific shortcuts are designed to make coding in R more efficient 18.
3. Data structures and objects
3.1 Introduction to data structures
R organizes data into various structures, each with specific properties for storing and manipulating information. Understanding these structures is fundamental for data analysis.
Common structures include vectors, lists, matrices, data frames, and tibbles 19.
3.2 Vectors
A vector is a one-dimensional collection of one or more values. All elements within a vector must be of the same class and type, such as all numbers or all characters.
Vectors are the primary input for many R functions 19.
📝 To create a numeric vector, you can use
c(1, 2, 3)22.
3.3 Atomic vectors
Atomic vectors are the most common type and include character, logical, and numeric data 21.
- Character: Stores text, words, numbers, or symbols enclosed in quotation marks. For example,
"8.1"is a character, not a number. - Logical: Stores
TRUEorFALSEvalues, which can also be represented asT/1andF/0respectively. - Numeric:
- Doubles: Double-precision numbers, which are the default for numeric values in R (e.g.,
1becomes1.00). - Integer: Exact whole numbers, specified by appending
L(e.g.,1L). - Other Numeric Symbols:
Infrepresents infinity (e.g.,1/0), andNaNrepresents "not a number" (e.g.,0/0). - Complex: Numeric values that include an imaginary number component (
i) 21.
📝 A character atomic vector can store text like
"8.1", which is distinct from the numeric value 8.1 21.
3.4 Creating vectors
Vectors are created using the concatenate function c(). To save a vector, assign it a name using the assignment symbol <- or -> 22.
- Naming conventions: Object names can include letters, numbers, periods (
.), and underscores (_), but should not start with a number or contain spaces. - Assignment: The
<-operator assigns data to a name, typically used outside functions. The=operator can also be used for assignment, both inside and outside functions 22.
| Vector Type | Example Creation |
|---|---|
| Numeric | c(1, 2, 3) |
| Integer | c(1L, 2L, 3L) |
| Logical | c(T, F, T, T) or c(TRUE, FALSE, TRUE, TRUE) |
| Character | c("string1", "string2") |
3.5 Vector manipulation
head(): Displays the firstnelements of a vector.tail(): Displays the lastnelements of a vector.- Duplicating objects: Assigning an existing vector to a new name creates a copy; modifying the copy does not affect the original 24.
- Overwriting objects: If an object is assigned the same name as an existing one, R will overwrite the original. Rerunning the original code and commenting out the overwriting code can fix this.
- Removing objects: Objects can be removed from the environment using the broomstick icon or specific commands 25.
- Combining vectors: Vectors can be combined using
c(). If vectors are of different classes, R will coerce them to a common class, typically character if a character vector is involved 26.
| Operation | Description |
|---|---|
| Combining same class | Elements are combined into a single vector of that class. |
| Combining different classes | R coerces elements to a common class (e.g., numeric to character). |
📝 To extract the 'Name' column from a data frame named
voting, you would use the syntaxvoting$Name30.
3.6 Checking vector properties
class(): Returns the data type of a vector.is.TYPE(): ReturnsTRUEorFALSEif the object is of the specified type (e.g.,is.numeric(),is.integer()) 27.
3.7 Lists
A list is a one-dimensional collection that can store elements of different types and lengths. Lists are often used to store the output of analyses 20.
3.8 Matrices
A matrix is technically a vector with a dimension attribute, allowing it to be treated as a two-dimensional object. Matrices are typically not used for direct data analysis in R 20.
3.9 Data frames
A data frame is a two-dimensional structure where all vectors (columns) must be the same length, but can be of different types. Data frames organize data such that each observation is a row and each variable is a column 20.
3.10 Creating data frames
Data frames are created using the data.frame() function, combining vectors as columns 27.
- Each vector used becomes a column in the data frame.
- The number of observations (rows) is determined by the length of the vectors.
- The number of variables (columns) is determined by the number of vectors provided 28.
| Data Structure | Creation Function | Dimensionality | Element Types |
|---|---|---|---|
| Vector | c() | 1D | Homogeneous (same class) |
| List | list() | 1D | Heterogeneous (different types/lengths) |
| Data Frame | data.frame() | 2D | Heterogeneous (columns must be same length) |
3.11 Data frame manipulation
head()andtail(): Display the top or bottomnrows of a data frame.view(): Opens a data frame in a separate tab for viewing 29.- glimpse(): Provides a vertical summary of columns, their classes, and a few values (requires library(tidyverse)).
skim(): Offers a more detailed summary of data frame columns, including type and statistical summaries (requireslibrary(skimr)).- **
$operator\ast\ast: Selects a specific column from a data frame, returning it as a vector. For example,voting$Nameextracts the 'Name' column 30. names(): Returns the names of columns in a data frame or elements in a list. It can also be used to rename columns.colnames(): Specifically used to get or set column names for 2D objects like data frames 31.length(): For a column vector,length()returns the number of elements.nrow(): Returns the number of rows in a 2D object.ncol(): Returns the number of columns in a 2D object.as.TYPE(): Coerces an object to a specified type, such asas.numeric(),as.character(), oras.data.frame()32.
3.12 Selecting data frame elements
Square brackets [] are used to select specific elements from data frames 33.
- Selecting rows and columns:
data.name[rows, columns]allows selection by row and column index or name. - Colon operator:
1:3creates a sequence of numbers, useful for selecting a range of rows or columns. - Cell: The intersection of a row and column is a single cell 33.
3.13 Tibbles
A tibble is a modern data frame from the tidyverse package that works similarly to a data frame but has some key differences in how it displays and handles data. Tibbles are designed to be more user-friendly for data analysis workflows 20.
3.14 Attributes
Attributes are metadata attached to R objects that provide additional information without altering the object's values. Common attributes include names, dimensions (dim), and classes 21.
3.15 Arrays
An array is a multi-dimensional data structure that can have three or more dimensions. While R supports arrays, they are less commonly used for typical data analysis compared to data frames 21.
| Data Structure | Dimensionality | Element Homogeneity | Primary Use Case |
|---|---|---|---|
| Vector | 1D | Homogeneous | Basic data storage, function input |
| List | 1D | Heterogeneous | Storing diverse outputs, complex objects |
| Matrix | 2D | Homogeneous | Mathematical operations, less common for analysis |
| Data Frame | 2D | Heterogeneous (columns) | Tabular data, observations and variables |
| Tibble | 2D | Heterogeneous (columns) | Modern tabular data, tidyverse integration |
| Array | nD | Homogeneous | Multi-dimensional data, specialized applications |
4. Statistical concepts and vocabulary
4.1 Data and variables
Data refers to the values measured or categories recorded for individual entities of interest, which are called observational or experimental units. The characteristics of these units are known as variables.
Variables can be broadly classified into quantitative and categorical types 34.
- Quantitative variables: These are numerical values.
- Discrete quantitative variables: Have distinct gaps between possible values, meaning they can only take specific, separate numerical values (e.g., the number of siblings).
- Continuous quantitative variables: Have no gaps between possible values, meaning they can take any value within a given interval (e.g., height or time).
- Categorical variables: These categorize observational units into different groups.
- Ordinal variables: Have categories that can be logically ordered (e.g., academic year: freshman, sophomore, junior, senior).
- Nominal variables: Have categories that are named but have no inherent order (e.g., favorite color).
- Identifier variables: These are unique to each individual and serve solely to identify them 34.
4.2 Distribution
A distribution describes the pattern of outcomes for a variable's values or categories. For categorical variables, this involves frequencies and variability.
For quantitative variables, distributions are characterized by their center, variability, and shape 35.
- Center: Measures indicating the typical value in a dataset.
- Mean: The average of all values.
- Median: The value that separates the lower 50% from the upper 50% of the data.
- Mode: The most frequently occurring value in the dataset.
- Variability: Measures indicating the spread or dispersion of data.
- Standard deviation: The average distance of each value from the mean.
- Interquartile Range (IQR): The range between the first quartile (25th percentile) and the third quartile (75th percentile). The second quartile is equivalent to the median.
- Range: The difference between the maximum and minimum values in the dataset 35.
📝 For a quantitative variable, the distribution can be described by its center (mean, median, mode), variability (standard deviation, IQR, range), and shape 35.
4.3 Tables for data summarization
Tables are used to organize and summarize data, particularly when examining one or more variables 35.
| Table Type | Purpose |
|---|---|
| Frequency table | Records total counts for each category of a single variable. |
| Relative frequency table | Displays the percentage of values falling into each category of a single variable. |
| Contingency table | Records totals for two or more variables and their interactions. |
4.4 Graphs for quantitative data
Various graphical methods are used to visualize the distribution of quantitative data 35.
- Histogram: Displays the frequency distribution of continuous quantitative data.
- Dot plot: Shows individual data points as dots above a number line.
- Box plot: Illustrates the distribution of quantitative data through quartiles, median, and potential outliers.
- Scatterplot: Used to visualize the relationship between two quantitative variables 35.
4.5 Explanatory and response variables
In statistical analysis, variables are often categorized by their role in explaining or responding to phenomena 36.
- Explanatory variable (IV): The variable used to understand or predict changes in another variable.
- Response variable (DV): The variable of primary interest, which is being studied for changes 36.
5. Mathematical operations and functions in R
5.1 Arithmetic and logical operators
R uses standard arithmetic operators for calculations, following the PEMDAS order of operations (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction). Logical operators are also available for conditional operations 38.
- Arithmetic operators:
+(addition)-(subtraction)*(multiplication)/(division)^(power)- Logical operators:
|(logical OR)&(logical AND)!(not)
5.2 Mathematical functions for scalar values
Mathematical functions in R can operate on scalar values (a single number). These functions perform specific mathematical transformations on the input value 38.
exp(value): Calculates the exponential of a value.log(value): Computes the natural logarithm.log10(value): Computes the base-10 logarithm.sqrt(value): Calculates the square root.abs(value): Returns the absolute value.factorial(value): Computes the factorial.sum(list of values): Calculates the sum of a list of values.floor(value): Rounds down to the nearest whole number.ceiling(value): Rounds up to the nearest whole number.round(value, digits = 0): Rounds to a specified number of decimal places or whole numbers.
5.3 Mathematical functions for vectors
Mathematical functions can also be applied to vectors, where the operation is performed element-wise If vectors of different lengths are used in an operation, R will recycle the shorter vector to match the length of the longer one 38 39.
- Element-wise operations: When applying arithmetic operators or functions to vectors, each element in one vector is processed with the corresponding element in another vector.
- Vector recycling: If vectors have different lengths, the shorter vector's elements are repeated to match the length of the longer vector 39.
📝 Applying
floor(sqrt(vector1))would first calculate the square root of each element invector1, and then apply thefloorfunction to each of those results 39.
5.4 Nesting functions
Functions can be nested within each other, meaning the output of one function becomes the input for another. This allows for more complex calculations to be performed sequentially 39.
- Order of operations: Nested functions are evaluated from the inside out 39.
📝
round(sqrt(vector1), digits = 0)first calculates the square root of each element invector1, and then rounds the result to the nearest whole number (the ones place) 39.
5.5 Rounding rules
R has specific rounding rules, particularly for numbers ending in.5 41.
- Rounding.5: Numbers exactly halfway between two integers are rounded to the nearest even number 41.
5.5rounds to6.6.5rounds to6.
5.6 Measures of center
Measures of center describe the typical or central value of a dataset 39.
mean(vector, na.rm = FALSE): Calculates the arithmetic average of the vector's elements.median(vector, na.rm = FALSE): Finds the middle value of a sorted vector.table(vector): Can be used to find the mode by showing the frequency of each value 39.
5.7 Measures of variability
Measures of variability quantify the spread or dispersion of data points in a dataset 39.
IQR(vector, na.rm = FALSE): Calculates the Interquartile Range, the difference between the third and first quartiles.sd(vector, na.rm = FALSE): Computes the standard deviation, a measure of the average distance of data points from the mean.range(vector, na.rm = FALSE): Returns the minimum and maximum values in the vector 39.
5.8 Summary information
The summary() function provides a quick overview of key statistical measures for a vector 40.
summary(vector): Outputs the minimum, first quartile, median, mean, third quartile, and maximum values 40.
| Statistic | Description |
|---|---|
| Min | Minimum value |
| 1st Qu. | First quartile (25th percentile) |
| Median | Median value (50th percentile) |
| Mean | Arithmetic average |
| 3rd Qu. | Third quartile (75th percentile) |
| Max | Maximum value |
5.9 Weighted mean
A weighted mean calculates an average where some data points contribute more than others. The w argument specifies the weights for each corresponding value 42.
weighted.mean(vector, w = weights): Computes the weighted average 42.
📝
weighted.mean(c(94.3, 86.1, 90.9), w = c(.4,.3,.3))calculates a weighted average where the scores94.3,86.1, and90.9have weights0.4,0.3, and0.3respectively 42.
5.10 Z-scores
A Z-score indicates how many standard deviations a particular data point is away from the mean of its dataset. It standardizes values, allowing for comparison across different distributions 40.
- Formula: z=sd of valuesvalue−mean of values.
- Calculation in R:
z.name <- (name - mean(name)) / sd(name)40.- This creates a new vector (
z.name) containing the Z-scores for each element in the originalnamevector 41.
📝
z.computer <- (computer - mean(computer)) / sd(computer)calculates the Z-score for each value in thecomputervector and stores them inz.computer41.
5.11 Quantile function
The quantile() function calculates specific percentiles or quantiles of a dataset 42.
quantile(name, probs = 0.__): Returns the value at the specified probability (quantile). Theprobsargument takes a decimal between 0 and 1 42.
5.12 Frequency tables and histograms
R can generate frequency tables and histograms to visualize data distributions 42.
- Frequency table:
table(vectorname)counts the occurrences of each unique value in a vector, and is case-sensitive. - Histogram:
hist(variable,...)creates a bar chart showing the frequency distribution of a continuous variable. Customization options include color, border, main title, and axis labels 42.
📝
hist(scores, col = "pink", border = "white", lwd = 1, main = "histogram of scores", xlab = "scores", ylab = "frequency")This code generates a histogram of the
scoresvariable with specific visual settings 42.
6. Data visualization and repetition
6.1 Box plots
A box plot is a graphical representation that displays the distribution of a dataset through quartiles. It is useful for identifying the median, interquartile range, and potential outliers 43.
To create a basic box plot in R, you use the boxplot() function with the vector name as the primary argument. Customizations can be added to enhance the plot's clarity and appearance 43.
- Basic syntax:
boxplot(vector_name). - Customizations:
col: Sets the color of the box.main: Sets the main title of the plot.ylab: Labels the y-axis.xlab: Labels the x-axis.horizontal = TRUE: Orients the box plot horizontally 43.
📝
boxplot(scores, col = "pink", main = "Boxplot of quiz scores", ylab = "Number of students", xlab = "Quiz scores", horizontal = TRUE)43.
6.2 The rep() function
The rep() function in R is used to repeat values or vectors a specified number of times. It is essential for creating sequences or patterned data 43.
The rep() function can be used with either the times argument or the each argument, but not both simultaneously 43.
| Argument | Description | Example |
|---|---|---|
| `times$ (single value) | Copies the entire vector end-to-end that many times. | rep(c('A', 'B', 'C'), times = 2) → A, B, C, A, B, C |
| times‘(vectorofvalues)∣Replicateseachelementofthevectorthenumberoftimesspecifiedbythecorrespondingvalueinthe‘times vector. | rep(c('A', 'B', 'C'), times = c(2, 1, 3)) → A, A, B, C, C, C | — |
| each (single value) | Replicates each element of the vector that many times before moving to the next element. | rep(c('A', 'B', 'C'), each = 2) → A, A, B, B, C, C |
When combining vectors using $rep()`, you can create new named vectors or combine existing ones 44.
- Creating named vectors:
namer.rep <- rep("vector name", times = ___ ). - Combining vectors:
new.name.rep <- c(vector1, vector2)This concatenates all values fromvector1andvector2into a single new vector 44.
📝 To create a vector where "vector name" is repeated 5 times:
namer.rep <- rep("vector name", times = 5) print(namer.rep)Output:
[1] "vector name" "vector name" "vector name" "vector name" "vector name"44.
7. Importing data into R
7.1 Importing data with base R functions
Importing data into R involves reading data from external files into data frames. Base R provides several functions for this purpose, with the choice of function often depending on the file type and its structure.
Key parameters include file for the file name, header to indicate if the first row contains column names, and sep to specify the delimiter used in the file 46 47.
read.table(): A general-purpose function for reading tabular data. It defaults toheader = FALSEand requires thesepargument to be explicitly set for non-whitespace delimiters.read.csv(): Specifically designed for comma-separated value files. It defaults toheader = TRUEandsep = ",".- read.delim(): Intended for tab-delimited files. It defaults to
header = TRUEandsep = "\t"46 47.
When importing, ensure the file is in the R session's working directory or provide the full file path. The getwd() function displays the current working directory 46.
| Function | Default Header | Default Separator | Typical Use |
|---|---|---|---|
| read.table() | FALSE | Whitespace | General tabular data |
| read.csv() | TRUE | , | Comma-separated files (.csv) |
| read.delim() | TRUE | \t | Tab-delimited files (.txt) |
7.2 Importing data with the readr package49
The readr package offers more modern and efficient functions for importing data, often handling common issues more gracefully than base R functions. These functions are generally faster and provide better feedback 47 48.
read_table(): Reads data where columns are separated by whitespace. It defaults tocol_names = TRUE.read_csv(): Reads comma-separated files. It defaults tocol_names = TRUE.- readdelim(): A flexible function that can read files with various delimiters. It attempts to guess the delimiter if not specified but allows explicit definition using the delim argument. It also defaults to
col_names = TRUE47.
A key feature of readr functions is their name repair mechanism. By default, readr attempts to create valid column names by replacing problematic characters (like periods) with underscores and ensuring uniqueness.
The name_repair = "universal" option provides a standardized way to handle these names, often by quoting them 48.
| readr Function | Base R Equivalent | Common Delimiter Handling |
|---|---|---|
| read_table() | read.table() | Whitespace |
| read_csv() | read.csv() | Comma (,) |
| read_delim() | read.delim() / read.table() | User-specified or guessed delimiter |
7.3 Handling file names and delimiters
When importing data, the delimiter is crucial as it tells R how to separate values into distinct columns. Common delimiters include commas (,) for .csv files and tabs (\t) or spaces for .txt files 46 47.
- For
.csvfiles,sep = ","in base R orread_csv()inreadris typically used. - For
.txtfiles,sep = "\t"for tab-delimited files is common, often used with read.delim() orread_table()46 47.
File names must be specified exactly, including their extensions (e.g., "data.csv"). If a file is not in the working directory, its full path must be provided 46.
📝 Importing a CSV file named
ClassData_csv.csvwith a header using base R:ClassData_csv_BaseR <- read.csv("ClassData_csv.csv", header = TRUE, sep = ",")46.
📝 Importing a text file named
Taboo_txt.txtwith tab delimiters usingreadr: tabootxtreadr<−readdelim("Tabootxt.txt",colnames=TRUE,delim="\t") 49.
7.4 Working with imported data
Once data is imported into a data frame, you can access its columns using the $ operator. This allows you to perform operations on the data, such as creating visualizations or performing calculations 48 49.
- Quantitative columns can be used for mathematical functions, like generating a histogram.
- Column names with special characters or spaces might require special handling, such as using backticks (
`) to reference them, especially when usingreadrwith name repair 48.
📝 Creating a histogram of the 'Salary' column from the
taboo_BaseRdata frame:hist(taboo_BaseR$Salary)49.
8. Exploratory Data Analysis (EDA) and data manipulation
8.1 Exploratory Data Analysis (EDA)
Exploratory Data Analysis (EDA) is used to understand data without formal analysis. It involves various summary statistics and visualizations to gain insights into the dataset's structure and characteristics.
EDA helps in identifying patterns, outliers, and relationships within the data before proceeding to more complex modeling 50.
Key components of EDA include:
- Five-number summary: Minimum, first quartile (Q1), median, third quartile (Q3), and maximum.
- Mean and standard deviation: Measures of central tendency and dispersion 50.
- Visualizations: Boxplots, scatterplots, and histograms to visualize data distributions and relationships 52 53.
8.2 Adding new columns to data frames
New columns can be added to an imported data frame to store derived information or new variables. This is typically done by assigning a vector of new data to a new column name within the data frame 50.
The syntax for adding a new column is: data.frame.name$new.column.name <- (new data) 50.
For example, to add a z-score column for 'HoursSlept': ClassDatatidyz.Hrs.Slept <- ((ClassData_tidyHoursSlept−mean(ClassDatatidyHoursSlept)) / sd(ClassData_tidyHoursSlept)) 50.
📝 To add a z-score column for 'HoursSlept' to the
ClassData_tidydata frame, you would use the following R code:$ClassData_tidy$z.Hrs.Slept <- ((ClassData_tidy$HoursSlept - mean(ClassData_tidy$HoursSlept)) / sd(ClassData_tidy$HoursSlept))$ [50](#page=50)
8.3 Frequency and contingency tables
Frequency and contingency tables are used to summarize categorical data. A frequency table displays the counts for categories of a single variable, while a contingency table displays the counts for combinations of two or more variables 51.
| Table Type | Description |
|---|---|
| Frequency Table | Displays counts for categories of ONE variable. |
| Contingency Table | Displays counts for combinations of TWO or MORE variables. |
The table() function in R can be used to create these tables:
table(df$column)creates a frequency table.table(df$column1, df$column2,...)creates a contingency table 51.
When creating contingency tables, the order of variables matters for presentation:
- The first listed variable typically appears vertically (rows).
- The second listed variable typically appears horizontally (columns) 51 52.
📝 To create a frequency table of the 'YearUVA' variable from the
ClassData_tidydata frame, you would usetable(ClassData_tidy$YearUVA). To create a contingency table showing the relationship between 'YearUVA' and 'Gender', you would usetable(ClassData_tidy$YearUVA, ClassData_tidy$Gender)51.
8.4 Boxplots
Boxplots are graphical representations used to visualize the distribution of a quantitative variable, often broken down by a categorical variable. They display the five-number summary and can reveal skewness, outliers, and differences between groups 52.
The formula notation for boxplots in R is: Y.Variable (Response/DV) ~ X.Variable (Explanatory/IV) 52.
A typical boxplot command: boxplot(Quantitative.Variable ~ Categorical.Variable, data = data.name, col = "color wanted", horizontal = FALSE) 52.
Additional arguments like xlab, ylab, main, and color can be used to customize the plot 52.
8.5 Scatterplots
Scatterplots are used to visualize the relationship between two quantitative variables. Each point on the plot represents an observation, with its position determined by the values of the two variables 53.
The basic syntax for creating a scatterplot is: plot(df$column1, df$column2) 53.
Using formula notation: plot(Y.Variable ~ X.Variable, data = data.name) 53.
The type argument can modify the appearance of the plot:
| Type Argument | Description |
|---|---|
| 'l' | Line plot |
| 'b' | Line with open circles |
| 'c' | Dashed line |
| 'o' | Line through open circles |
8.6 Graph parameter settings
The par() function in R allows for the modification of graphical parameters that affect how plots are displayed within the current graphics environment 53.
Commonly used parameters include mfrow() and mfcol() for arranging multiple plots in a grid:
par(mfrow = c(rows, columns))arranges plots in a grid, filling by row.par(mfcol = c(rows, columns))arranges plots in a grid, filling by column 53.
These settings remain active until changed back, for example, to par(mfrow = c(1,1)) 53.
9. Summary of R topics
9.1 R packages and data structures
This section covers essential R functionalities, including package management, data structures, and basic data manipulation. Understanding these building blocks is crucial for any data analysis task in R 55.
- Package management:
install.packages("____")is used to download and install packages from repositories.library(___)loads an installed package into the current R session, making its functions available.- Vectors:
- Vectors are one-dimensional arrays that can hold elements of the same data type.
- Assignment of values to vectors is done using the
<-operator. head()displays the first few elements of a vector, whiletail()displays the last few.- Vectors can be combined using functions like
c(). is.type()checks if a vector is of a specific data type (e.g.,is.numeric()).class()returns the data type of a vector.length()returns the number of elements in a vector.- Data frames:
- Data frames are two-dimensional structures that can hold columns of different data types, similar to a table.
colnames()retrieves or sets the names of the columns in a data frame.nrow()returns the number of rows in a data frame.- Individual elements in a data frame are accessed using
[row, column]indexing. names()can be used to access or set names for elements, often used with lists or data frames 55.
9.2 Mathematical and statistical functions in R
R provides a rich set of functions for performing mathematical operations and calculating statistical measures on data. These functions are fundamental for summarizing and understanding data distributions 55.
- Mathematical functions: R supports various mathematical operations on vectors, including:
center(e.g.,mean())variability(e.g.,sd(),IQR())log10(),exp(),log()(natural logarithm)sqrt(),abs()floor(),ceiling(),round()factorial()58.- Statistical measures: R can compute several key statistical values:
mean(): calculates the average of a vector.median(): finds the middle value of a sorted vector.sd(): computes the standard deviation.IQR(): calculates the interquartile range, representing the spread of the middle 50% of data.range(): returns the minimum and maximum values.summary(): provides a quick statistical summary, including min, max, median, mean, and quartiles.quantile(): calculates quantiles for specified probabilities.- Z-scores: A z-score measures how many standard deviations an element is from the mean.
- The formula for a z-score is:
(data.name$column.name - mean(data.name$column.name)) / sd(data.name$column.name)57.
9.3 Data visualization and variable types
R facilitates the visualization of data distributions and allows for the classification of variables into different types, which guides the choice of analytical methods 55.
- Data visualization: R can generate various plots to visualize data distributions:
- Box plots: display the distribution of data through quartiles.
- Histograms: show the frequency distribution of continuous data.
- Variable types: Understanding variable types is crucial for analysis:
- Quantitative variables: represent numerical values.
- Discrete: can only take specific, separate values (e.g., number of children).
- Continuous: can take any value within a range (e.g., height, temperature).
- Categorical variables: represent qualities or characteristics.
- Ordinal: categories have a natural order (e.g., education level: high school, bachelor's, master's).
- Nominal: categories have no inherent order (e.g., colors: red, blue, green).
- Distribution of a variable:
- For continuous quantitative variables, focus is on measures of center, variability, and shape.
- For categorical variables, focus is on frequencies within each category 55.
9.4 Importing data into R 57 59
R offers robust functions for importing data from various file formats, enabling seamless integration of external datasets into the analysis workflow 55.
- File properties for import: Key aspects to consider when importing data include:
- File extension/type: Determines the appropriate reading function (e.g.,
.csv,.txt,.xlsx). - Delimiter: The character used to separate values within a row (e.g., comma, tab, whitespace).
- Header information: Whether the first line of the file contains column names (
header = TRUE) or not (header = FALSE) 55. - Default R functions for data import:
read.csv("name in file", header = TRUE, sep = ","): Reads comma-separated values files.read.table("name in file", header = TRUE, sep = "\t"): Reads tab-delimited files.- read.delim(): Similar to
read.table, often used for tab-delimited files. readrpackage functions: Thereadrpackage provides faster and more consistent data import functions:read_csv("name in file"): Reads comma-separated values files.read_tab("name in file"): Reads tab-delimited files.- readdelim("nameinfile",delim="\t"): A general function for delimited files.
- Default delimiters:
- CSV files typically use a comma (
,) as a separator. - Tab-delimited files use a tab (
\t). - Whitespace can also be used as a delimiter for general table formats 57 59.
| Function | Delimiter | Header Argument |
|---|---|---|
| read.csv | , | TRUE/FALSE |
| read.table | \t | TRUE/FALSE |
| read_csv | , | Implicitly TRUE |
| read_tab | \t | Implicitly TRUE |
9.5 Data manipulation and analysis in R 55 59
R offers powerful tools for manipulating data frames and performing various analytical tasks, from adding new columns to creating summary tables 56.
- Adding columns to data frames: New columns can be added to an existing data frame using the
$operator to assign values. imported.data.name$new.column.name <- (new data): This syntax allows for the creation of new columns, such as calculated z-scores for an existing column.- Frequency and contingency tables: R can generate tables to summarize data:
table(df$column): Creates a frequency table for a single categorical variable.table(df$column, df$column,...): Generates a contingency table to show the frequencies of two or more categorical variables simultaneously 56.rep()function: This function is used to repeat elements:rep(x, times): Repeats the entire vectorx,timesnumber of times.rep(x, each): Repeats each element of vectorx,eachnumber of times 55 59.
| Repetition Type | Example Input | Output |
|---|---|---|
| Times | rep(1:3, times = 2) | 1 2 3 1 2 3 |
| Each | rep(1:3, each = 2) | 1 1 2 2 3 3 |
- Data visualization functions:
- Box plots can be created using functions like
boxplot(scores)59.
| Data Structure | Access Method | Example |
|---|---|---|
| 1D Vector | [index | my_vector3 |
| 2D Data Frame | [row, column | my_dataframe2 4 |
summary()function:summary(data.name$column.name): Provides a statistical summary for a specific column.summary(data.name): Provides a summary for all columns in a data frame 57.
📝 To add a column of z-scores for a column named 'height' in a data frame called 'patients', you would use:
patients$height_zscore <- (patients$height - mean(patients$height)) / sd(patients$height)56 57.
© 2026 Maeve. All rights reserved. This content is protected by copyright.