data science
Table of contents
- Stat 1601
- FUNCTIONS
- NAMING
- FLASHCARDS
- unit 1
- 8/25 lecture
- 8/27 lecture 1.1
- 8/28 lab
- 9/1 lecture 1.1-.2
- 9/3 lecture 1.2
- 9/8 lecture 1.2
1. Stat 1601
1.1 R and RStudio Basics
This section introduces fundamental concepts for using R and RStudio, focusing on package management, data structures, and basic operations. Understanding these building blocks is crucial for subsequent data analysis tasks 1 4.
1.2 Installing and Running Packages
Packages in R extend its functionality. They can be installed from online repositories and then loaded into the current session to make their functions available.
- Install package: Use the
install.packages()function to download and install a package. - Run package: Use the
library()function to load an installed package into your R session, making its functions accessible 4 9.
📝 To install a package named "dplyr", you would use the command
install.packages("dplyr")4.
1.3 Creating and Manipulating Vectors
Vectors are fundamental one-dimensional data structures in R. They can hold elements of a single class, such as numbers, characters, or logical values.
- Vector creation: The
c()function combines elements into a vector. - Vector classes:
- Numeric: Includes integers (
1L,2L) and general numbers (doubles). - Logical: Represents TRUE or FALSE values (
T,F,TRUE,FALSE,1,0). - Character: Stores text strings.
- Checking class: Functions like
is.numeric(),is.character(), andis.logical()check the class of a vector9. - Defining class: The
class()function returns the data type of an object 4 10.
📝 To create a vector named
my_vectorcontaining the numbers 1, 2, and 3, you would usemy_vector <- c(1, 2, 3)4.
1.4 Combining and Inspecting Vectors
Vectors can be combined to form larger vectors, and functions exist to view the beginning or end of a vector's contents.
- Combining vectors: Assign the result of
c(vector1, vector2)to a new or existing vector name. Elements must be of a compatible class. - Viewing first elements:
head(vector_name, n = _)displays the firstnelements. - Viewing last elements:
tail(vector_name, n = _)displays the lastnelements 4 10.
1.5 Data Frames
Data frames are two-dimensional data structures that can hold columns of different data types, making them suitable for tabular data.
- Data frame creation: The
data.frame()function creates a data frame from named objects (like vectors) 4 10.
1.6 Accessing Object Names
R provides specific ways to access the names associated with objects, particularly column names in data frames.
- Dollar sign notation: The
USDsymbol is used to access elements within objects, especially columns in data frames. names()function: Outputs labels for 1D objects (vectors, matrices) and column names for 2D objects (data frames, tibbles) 4.colnames()function: Specifically outputs column names for 2D objects like data frames or tibbles 5 10.
2. FUNCTIONS
2.1 Core R Functions and Concepts
This section delves into the nature of functions in R, their components, and how they are executed. Functions are the building blocks for performing operations and simplifying complex tasks 3 9 18.
2.2 Understanding Functions and Arguments
Functions are pre-written sets of instructions that perform specific tasks. They often require inputs, known as arguments, to operate correctly.
- Function definition: A function is a set of instructions designed to simplify tasks in R.
- Arguments: These are the inputs provided to a function, allowing for customization of its behavior 9 18.
📝 Arguments are the inputs provided to a function, allowing for customization of its behavior 9 18.
2.3 Executable vs. Unexecutable Code
R distinguishes between lines of code that are executed and those that are not. This distinction is important for code organization and readability.
- Executable lines: These are typically displayed in blue or black and represent commands or function calls that R will process.
- Unexecutable lines: These are ignored by R during execution and are used for organizational purposes. They include:
- Headings: Lines starting with
#and followed by specific characters (-,=) to denote sections. - Visual cuts: Lines used to create visual breaks in the code, often using underscores 18.
- Comments: Explanatory text that R does not interpret as code 9.
2.4 Running Code in R
Executing code in R involves sending commands to the R interpreter. The interface provides visual cues for incomplete commands.
- Execution: Typically done by pressing
Command + Enter(orCtrl + Enteron Windows). - Incomplete line indicator: A
+symbol appears if a line of code is not complete, indicating R is waiting for more input 18.
2.5 Packages and Their Management
Packages are collections of R functions, data, and documentation that extend R's capabilities. Managing packages involves installing and loading them.
- Installing packages:
- Point-and-Click: Using RStudio's graphical interface.
install.packages(): A function to install packages programmatically.- Loading packages:
library(): Loads a package into the current R session.require(): Similar tolibrary(), often used within functions 9.
3. NAMING
3.1 Conventions for Object Names in R
Naming objects in R follows certain conventions and rules that impact how code is written and interpreted. Consistent naming is crucial for code clarity and maintainability 6.
3.2 Assignment Operators
R uses several symbols to assign values to objects. Understanding these is key to storing and retrieving data.
- Assignment: Values are assigned to object names using assignment operators.
< -: The primary and most common assignment operator in R.->: Assigns the value on the left to the object on the right.=: Also used for assignment, though< -is generally preferred for clarity 10.
📝 To assign the value 5 to an object named
my_variable, you can usemy_variable <- 54.
3.3 Naming Mechanisms
The process of assigning values to objects involves specific mechanisms, including the use of assignment operators and functions for object manipulation.
- Saving objects: The assignment symbol is used to store results or data into named objects.
c()function: Used to create vectors by combining elements.head()andtail(): Functions to view the beginning or end of an object.view()andView(): Functions to display data frames or other objects in a viewer pane.- glimpse(): Provides a concise summary of a data frame's structure.
class(): Returns the data type of an object.is.TYPE(): Functions likeis.numeric(),is.character(),is.logical()check an object's class 10.
4. FLASHCARDS
4.1 Key R Concepts and Functions
This section consolidates essential R concepts and functions, presented as flashcards for quick review. It covers data structures, classes, attributes, and various utility functions 8 9 10 11 12.
4.2 Data Structures in R
R supports several data structures, each suited for different types of data organization.
- Vectors: One-dimensional arrays that hold elements of the same class.
- Lists: Can hold elements of different classes, including other lists.
- Matrices: Two-dimensional arrays where all elements must be of the same class.
- Data Frames: Two-dimensional structures that can hold columns of different classes, resembling tables 9 10.
- Tibbles: A modern version of data frames, part of the tidyverse package, with some differences in behavior.
- Arrays: Multi-dimensional generalizations of matrices.
📝 A data frame can be created using
data.frame(column1 = c(1, 2, 3), column2 = c("A", "B", "C")), wherecolumn1is numeric andcolumn2is character 9.
4.3 Data Classes and Attributes
Data in R is organized by class, and objects can have additional properties called attributes.
- Classes: Define the type of data an object can hold.
- Numeric:
- Doubles: Standard floating-point numbers.
- Integer: Whole numbers, often denoted with
L(e.g.,5L). - Character: Text strings.
- Logical: Boolean values (
TRUE,FALSE). - Complex: Numbers with real and imaginary parts.
- Factor: Used for categorical data, storing data as integers with labels 9.
- Attributes: Properties associated with an object.
- Names: Labels for elements within an object.
- Dimensions: Specify the size and shape of an object (e.g., rows and columns).
- Class: The data type of the object 10.
4.4 Utility Functions for Data Manipulation
A variety of functions are available for creating, inspecting, and transforming data objects.
- Creation and Assignment:
c(): Creates vectors.<-,->,=: Assignment operators.data.frame(): Creates data frames.rep(): Repeats elements.- Inspection:
head(),tail(): View first/last elements.view(),View(): Display data.- glimpse(): Summarize data frame structure.
class(): Get object class.is.TYPE(): Check object class (e.g.,is.numeric()).names(),colnames(): Get names/column names.length(): Number of elements in a vector.nrow(),ncol(): Number of rows/columns in 2D objects.summary(): Provides a statistical summary of data.table(): Creates frequency tables 12.- Transformation:
as.TYPE(): Converts an object to a specified class (e.g.,as.numeric()).Square-Brackets: Used for subsetting objects based on indices 10.
4.5 Statistical Measures and Functions
R provides functions to calculate various statistical measures for understanding data distributions.
- Measures of Center:
- Mean: Average value.
mean(). - Median: Middle value when data is sorted.
median(). - Mode: Most frequent value (less directly supported by a single base R function, often requires custom calculation or packages).
- Measures of Variability:
- Standard Deviation: Measure of data spread around the mean.
sd(). - Interquartile Range (IQR): The range between the first and third quartiles.
IQR(). - Range: Difference between the maximum and minimum values.
range()11. - Other Statistical Functions:
quantile(): Calculates quantiles.min(),max(): Minimum and maximum values.z-score formula: Standardizes a value.weighted.mean(): Calculates a mean with specified weights 12.
📝 To find the average of a vector named
my_data, you would use the functionmean(my_data)12.
4.6 Graphical Representations
R offers functions to create various plots for visualizing data distributions and relationships.
- Histograms: Show the distribution of a continuous quantitative variable.
hist(). - Boxplots: Display the distribution of a quantitative variable, showing median, quartiles, and outliers.
boxplot()12. - Other plots: Dotplots, scatterplots, bar charts, pie charts, and frequency tables are also used for visualization 11.
4.7 Arithmetic and Mathematical Functions
R includes a comprehensive set of operators and functions for mathematical calculations.
- Arithmetic Operators:
+,-,*,/: Basic arithmetic operations.^: Exponentiation.- Mathematical Functions:
exp(): Exponential function (ex).log(),log10(): Logarithm functions.sqrt(): Square root.abs(): Absolute value 11.factorial(): Factorial of a number.sum(): Sum of elements.floor(),ceiling(): Round down/up to the nearest integer.round(): Rounds to a specified number of decimal places 12.
5. unit 1
5.1 Introduction to Statistical Concepts
This unit introduces foundational concepts in statistics, including the distinction between observational and experimental units, types of variables, and how to describe their distributions 13.
5.2 Observational vs. Experimental Units
Understanding the source of data is critical in statistical analysis.
- Observational units: The individuals or items on which data are collected.
- Experimental units: The individuals or items to which treatments are applied in an experiment 13.
📝 In a study, the observational units are the individual students, and if a new teaching method is applied to one group of students but not another, the students are the experimental units to which the treatment (teaching method) is applied 13.
5.3 Variables of Interest
Variables are characteristics that can take on different values for different observational units. They are broadly categorized into quantitative and categorical types.
- Quantitative variables: Measure numerical quantities.
- Discrete: Can only take specific, separate values (e.g., number of siblings).
- Continuous: Can take any value within a range (e.g., height, weight).
- Categorical variables: Represent groups or categories.
- Nominal: Categories with no inherent order (e.g., color, gender).
- Ordinal: Categories with a meaningful order (e.g., education level: high school, bachelor's, master's) 13.
5.4 Distribution of a Variable
The distribution of a variable describes how frequently different values occur. The way to describe it depends on the variable's type.
- Continuous Quantitative: Described by measures of center, variability, and shape.
- Categorical: Described by frequencies or relative frequencies in each category.
- Discrete Quantitative: Can be described using methods for both continuous and categorical variables, often focusing on specific values and their frequencies 13.
5.5 Frequency Tables and Visualizations
Frequency tables summarize the counts of observations in different categories or ranges, and various plots visualize these distributions.
- Frequency Table: Shows the count of observations for each category or value.
- Relative Frequency Table: Shows the proportion or percentage of observations for each category or value.
- Contingency Table: Used to display the frequency distribution of two categorical variables simultaneously.
- Visualizations:
- Histogram: For continuous quantitative data.
- Dotplot: For discrete quantitative or categorical data.
- Boxplot: For continuous quantitative data13.
- Scatterplot: For visualizing the relationship between two quantitative variables.
- Bar chart/Bar plot: For categorical data.
- Pie chart: For categorical data, showing proportions 11.
6. 8/25 lecture
6.1 R Code Execution and Structure
This lecture segment clarifies how R interprets and executes code, focusing on the distinction between executable and non-executable lines, and the role of functions and their arguments 15 17 18.
6.2 Executable and Non-Executable Code Lines
R differentiates between lines of code that perform actions and those that serve other purposes like organization or explanation.
- Executable Lines: These are commands or function calls that R processes. They are often displayed in blue or black in RStudio, indicating their executable nature.
- Non-Executable Lines: These lines are ignored by R during execution. They are used for:
- Comments: Explanatory text to help understand the code.
- Headings: Used to structure the script, often starting with
#and followed by visual separators like-or=. - Visual Cuts: Lines like
#______________________that create visual breaks for readability 18.
📝 A comment line in R, such as
# This is an explanatory note, is non-executable and ignored by R during code processing 18.
6.3 Functions and Arguments in R
Functions are fundamental to R programming, providing reusable blocks of code. They often take arguments to modify their behavior.
- Function: A set of instructions that R executes to perform a specific task, simplifying complex operations.
- Arguments: Inputs provided to a function that customize its operation 18.
6.4 Running Code and Incomplete Commands
Executing code in R involves sending commands to the interpreter. R provides feedback when a command is not fully entered.
- Running Code: Typically initiated by pressing
Command + Enter(orCtrl + Enter). - Incomplete Command Indicator: If a line of code is not complete (e.g., an opening parenthesis is not closed), R displays a
+symbol, indicating it expects further input to finish the command 18.
7. 8/27 lecture 1.1
7.1 R code structure and execution
R code is written in scripts, which must be manually saved. Unsaved changes are indicated by a red tab.
Comments, which are executable lines of code, are created using a # symbol at the beginning or middle of a line. Executable code is written in black text 20.
Functions are preset tasks in R, are case-sensitive, and start and end with parentheses (). Arguments are parts of a function, separated by commas within the parentheses.
NA represents a missing value and affects how a function handles it 20.
Headings in R scripts require at least one #, =, or - at the beginning of the line, followed by at least four of the same character. A single # denotes a level one heading, while ## denotes a level two heading.
Visual cuts, indicated by # ____________________________, are used for organization and are not headings 20.
To run R code, place the cursor in the line of code and press Command + Return. Multiple lines can be run by highlighting them.
The > symbol in the console indicates readiness for new code, while + signifies that something is still running, such as a line of code split across multiple lines. Pressing Escape returns the console to the > prompt 21.
8. 8/28 lab
8.1 File paths and shortcuts in R
A file path acts as an address, providing directions to a specific file on a computer. R requires the exact file path to access data 23.
General keyboard shortcuts and R-specific shortcuts are available to improve efficiency when working with R 23 24.
9. 9/1 lecture 1.1-.2
9.1 Data structures and objects in R
R uses specific syntax for operations, such as (2 + 2) for addition, rather than (2+2). Sequences of numbers can be quickly created using a range, like 400:500, which generates numbers from 400 to 500 with a step of one 26.
Packages are installed using the install.packages("package_name") function or through the R interface. Packages are activated using library(package_name) or require(package_name).
Activating tidyverse, for example, may override certain base R functions 26.
9.2 Types of data structures
R organizes data into various structures:
- Vectors (1D): Collections of one or more values of the same class and type (e.g., all numbers or all characters). They are what are plugged into functions and often returned by analyses 26.
- Lists (1D): Collections of vectors that can be of different types and lengths, often used in the output of analyses.
- Matrix (2D): Technically a vector with a dimension attribute, treated as either 1D or 2D depending on the context. Matrices are typically not used for data analysis.
- Data Frame (2D): Composed of vectors of the same length but potentially different types. Data frames organize data where each observation is a row and each variable is a column.
- Tibble (2D): The tidyverse version of a data frame, functioning similarly 27.
- Array (nD): Data structures that can have three or more dimensions 28.
📝 R organizes data into vectors (1D), lists (1D), matrices (2D), data frames (2D), tibbles (2D), and arrays (nD) 26.
9.3 Types of vectors (atomic)
Atomic vectors are the fundamental building blocks for data in R:
- Character: Stores strings or text, including words, numbers, and symbols enclosed in quotation marks.
- Logical: Stores
TRUEorFALSEvalues (must be capitalized).Tis equivalent to1, andFis equivalent to0. - Numeric:
- Doubles: Double-precision numbers, which are the default for numbers unless specified as integers.
- Integer: Exact integer values, denoted by an
Lsuffix (e.g.,1L). All integers can be treated as doubles. - Other Numeric Symbols:
Infrepresents infinity or "not a number" (e.g.,1/0), andNaNrepresents values considered not a number (e.g.,0/0). - Complex: Numeric values that include an imaginary number component (
i) 28.
9.4 Attributes
Attributes are metadata attached to an object, providing additional information without affecting the object's values.
- Names: Can be assigned to elements within vectors or to columns and rows in 2D objects.
- Dimensions (dim): Specify the dimensionality of an object (1D, 2D, nD).
- Classes: Indicate the type of data within an object 28.
9.5 Creating and assigning vectors
Vectors are created using the concatenate function c(). For example, c(8, 6,...) creates a numeric vector.
The output in black text in the console indicates unsaved data 29.
Saving data requires a name, an assignment symbol (<- for left assignment, traditionally used outside functions; -> for right assignment, used inside functions; or = for assignment both ways), and the function or data being created. Object names cannot start with a number and should avoid symbols like ! or ?.
Spaces in names are not allowed 29 30.
10. 9/3 lecture 1.2
10.1 Working with vectors and data frames
R can create vectors of different types:
- Doubles:
c(1, 2, 3). - Integers:
c(1L, 2L, 3L). - Logic:
c(T, F, T, T)orc(TRUE, FALSE, TRUE, TRUE)32.
The head() function displays the first n elements of an object (defaulting to 6), while tail() displays the last n elements 32.
Duplicate objects can be created by assigning an existing object to a new name. Modifying the duplicate does not affect the original object 32.
Naming mistakes occur when an object is assigned the same name as a previously defined one. R will override the original.
To fix this, re-run the original code and add a # comment to the line that caused the override 33.
Objects can be removed from the environment using the broomstick icon 33.
Vectors can be created for integers, logical values, and characters.
- Character vectors: Commas must be outside quotation marks. Spaces can be included within strings 33.
Common mistakes include using quotation marks around numbers or logical values, which converts them into characters 33.
10.2 Combining vectors
Vectors can be combined using c(), but they must be of the same class. If vectors of different types are combined, R will coerce them to the most general type (e.g., numbers become characters) 34 35.
The class() function identifies the data type of an object, while is.TYPE() functions (e.g., is.numeric()) return TRUE or FALSE based on whether the object meets the specified type condition 35.
10.3 Data frames 26 27
Data frames are 2D structures used to store heterogeneous data, where each observation is a row and each variable is a column. They are created using the data.frame() function, listing the vectors to be combined as arguments, optionally with column names assigned 35 36.
| Data Structure | Description |
|---|---|
| Vector | 1D collection of same-type values |
| List | 1D collection of different-type vectors |
| Matrix | 2D vector with dimension attribute |
| Data Frame | 2D with same-length vectors of different types |
| Tibble | Tidyverse version of Data Frame |
| Array | nD structure |
📝 To create a data frame named
votingwith columnsName,Age, andVote, you would first create vectors for each column:Name <- c("James", "Helen", "Siegfried"),Age <- c(22, 15, 19), andVote <- c(TRUE, FALSE, TRUE), then combine them usingvoting <- data.frame(Name, Age, Vote)36.
11. 9/8 lecture 1.2
11.1 Advanced data frame operations39 40
The c() function concatenates 1D elements, while data.frame() combines elements into a 2D structure. A data frame with 3 observations has 3 rows, and 3 variables means 3 columns 38.
The head() and tail() functions can be applied to 2D objects to view the top and bottom six values, respectively. The view(vector_name) function opens a summary table of the data 38.
The glimpse() function, available after loading tidyverse, lists columns vertically along with their class and other information 39.
The skimr package provides the skim() function (library(skimr); skim(data_frame_name)) which summarizes the data frame, detailing column types and statistics 39.
The EUR symbol is used to identify specific columns within a data frame (e.g., votingEURName). This selection results in a 1D vector 39.
The names() function can be used with 1D and 2D objects to add, redefine, or list the names of columns. The colnames() function specifically changes column names 40.
| Function | Purpose |
|---|---|
| c() | Concatenate 1D elements |
| data.frame() | Create a 2D data frame |
| head() | View first n elements (default 6) |
| tail() | View last n elements (default 6) |
| view() | Open data summary table |
| glimpse() | List columns vertically with class info |
| skim() | Summarize data frame statistics |
| EUR | Select specific column within a data frame |
| names() | Add/redefine/list names of objects/columns |
| colnames() | Change column names |
© 2026 Maeve. All rights reserved. This content is protected by copyright.