R and RStudio Basics
BeginnerLesson 1 of 7 in Data Analysis with R Course
What you will learn
- Explain how R and RStudio work together, find your way around the RStudio window, and run your first calculations and comparisons in the console.
- Tell R and RStudio apart and find your way aroundInstall R and RStudio in the right order, recognize the four panes, and read what the console shows while it works.
- Use R as a calculator and compare valuesCalculate with R's arithmetic operators and math functions, predict the order of operations, and compare values to get TRUE or FALSE.
- Tell R and RStudio apart and find your way around
- Store values in named objects, keep track of them in your session, and use R's functions with the right arguments.
- Create, name and manage objectsAssign values to objects with clear, valid names, use them in calculations, and know what happens when you change or remove them.
- Call functions and set their argumentsCall functions with arguments by position and by name, use default values, nest calls, and keep the results you need.
- Create, name and manage objects
- Build vectors, recognize R's main data types, predict how R converts between them, and calculate with and select from vectors.
- Build vectors and recognize their typesCreate vectors with c(), sequences and repetition, and tell logical, integer, double and character values apart.
- Predict and control type conversionPredict how R coerces mixed values, convert types on purpose, and catch the warnings that signal failed conversions.
- Calculate with vectors and select elementsApply vectorized arithmetic and summary functions, predict recycling, and pick elements by position or by condition.
- Build vectors and recognize their types
- Install and load packages, use the tidyverse's core packages, resolve conflicts between function names, and chain steps with the pipe.
- Install, load and update packagesTell installing from loading, call package functions with ::, and fix the errors that come from missing or unloaded packages.
- Use the tidyverse and resolve conflictsLoad the core tidyverse packages, read the startup message, choose between functions with the same name, and chain steps with the pipe.
- Install, load and update packages
- Keep your analysis in saved scripts, organize files in RStudio projects with relative paths, and write code that others can read and rerun.
- Write, run and save R scriptsWrite code in the script editor, run it line by line or as a whole, structure it with comments and sections, and save it under good file names.
- Use projects, the working directory and file pathsKeep each analysis in an RStudio project, use relative paths from the working directory, and set RStudio so scripts, not saved workspaces, are the source of truth.
- Write readable code in a consistent styleName objects, space code, break lines and comment consistently, following the tidyverse style guide, and let tools tidy code for you.
- Write, run and save R scripts
- Use R's documentation to learn how a function works, read error messages, search well, and ask questions with a reproducible example.
- Use help pages and documentationOpen and read R help pages, run their examples, search when you don't know a function's name, and use vignettes, package websites and cheatsheets.
- Read error messages and ask for help wellTell errors, warnings and messages apart, recognize common errors and their fixes, search for solutions, and share a minimal reproducible example.
- Use help pages and documentation
R and RStudio study guide
1Get started with R and RStudio
Your first R commands connect what you type with what the console returns. RStudio gives those commands a workspace: one pane for writing, another for running, and others for inspecting results or finding help. Learn how to read the prompts before building calculations. Arithmetic, function calls, and true/false comparisons then give you a small set of tools for checking both numbers and conditions.
1.1 Meet R, RStudio, and the console
R is the computing engine: a free, open-source language and environment for working with data, statistics, and graphics. RStudio is an integrated development environment (IDE) from Posit. It gives you a place to write code, run it, inspect objects, view plots, and read help.
Install and open your tools
Install R from CRAN, choosing your operating system. Then install the free RStudio Desktop from Posit. RStudio needs an R installation; R can also run by itself in a terminal. Positron is another editor for R and Python. Your R code works across these editors, although their controls differ.
Type R.version.string in the console to see your installed R version. You type the command after the prompt, without copying the prompt itself.
Find the four panes
With a script open, RStudio's default layout puts the source editor at the top left and the console below it. The source editor holds code you can save. The console sends commands to R and displays their results.
The top-right Environment pane shows objects created in the session; the History tab records commands. The bottom-right pane has Files, Plots, Packages, Help, and Viewer tabs. For example, open Help to read a function's documentation and Plots to inspect a graph. Change pane positions under Tools > Global Options > Pane Layout if needed.
Read a console exchange
Enter this command:
1 + 2
R prints:
[1] 3
The answer is 3. The [1] says the first printed value on this line is element 1. It is a position label, not a value to include in a calculation. When a long vector wraps onto another line, that line's label gives the position of its first value. Where the wrap happens depends on the console width.
A > at the start of the input line means R is ready for a command. A + there is a continuation prompt: R is waiting for the rest of an unfinished command. Try typing round(3.14159, 2 without its closing parenthesis. R cannot finish that call yet. Type ) and press Enter, or press Esc to cancel the incomplete command. An unmatched quote can produce the same waiting state.
Try a line, then keep it
Use the up arrow to recall a command and edit it. Tab completion helps finish object and function names and find arguments. Ctrl+L clears the console display; the objects you created remain in memory. Clearing a screen and clearing a session are different actions.
The console is useful for a quick calculation or checking an object's value. Keep the code for an analysis in a saved script, where you can read its order and run it again. A practical pattern is to try a command, adjust it until it works, and keep the working form in your script. RStudio shortcuts here are given as Windows/Linux first and Mac second: Ctrl+Enter / Cmd+Enter, for example.
Key Takeaways
- R performs the calculations; RStudio provides an editor and other tools around R.
- Install R before RStudio Desktop.
- The console runs code; the source editor holds code to save.
>means ready; a leading+means a command is incomplete.- Output labels such as
[1]identify positions, and Ctrl+L only clears the display.
1.2 Calculate and test conditions
R can calculate a result or test a statement. A calculation returns a number; a comparison usually returns TRUE or FALSE. Both are useful when you start checking data.
Choose the operation
Use + and - for addition and subtraction, * for multiplication, / for division, and ^ for powers. Integer division %/% counts whole divisions; %% gives the remainder. For example, 7 / 2 gives 3.5, 5 %/% 2 gives 2, and 5 %% 2 gives 1. For a whole number n, n %% 2 == 0 tests whether it is even.
R evaluates powers first, then %/% and %%, then multiplication and division, then addition and subtraction. Parentheses change the order. Thus 1 + 2 * 3 gives 7, while (1 + 2) * 3 gives 9. In 2 * 5 %% 3, R finds the remainder of 5 divided by 3 first, giving 2 * 2, or 4.
Multiplication and division group left to right: 100 / 10 / 2 gives 5. Powers group right to left: 2^3^2 means 2^(3^2) and gives 512. A power also comes before a leading minus: -2^2 gives -4, but (-2)^2 gives 4.
For a cyclist traveling 42 km in 1.5 hours, 42 / 1.5 gives an average speed of 28 km/h. To convert 72 km/h to meters per second, write 72 * 1000 / 3600. Multiplying by meters per kilometer and dividing by seconds per hour gives 20 m/s.
Call a math function
sqrt(16) returns 4, abs(-3) returns 3, and exp(1) returns about 2.718282. log() uses natural logarithms. For base 10, use log10(100) or log(100, base = 10), both giving 2.
round(3.14159, digits = 2) gives 3.14. Exact halfway cases go to the even final digit: round(2.5) gives 2 and round(3.5) gives 4. Decimal storage can affect apparent halfway cases, so these exact halves are useful examples of the rule.
R normally displays 7 significant digits while retaining about 15–16 digits of precision for ordinary doubles. 22 / 7 prints 3.142857; the stored result retains more precision. Use a decimal point in code. A comma separates arguments: round(2,5) rounds 2 to five decimal places and returns 2.
Compare values
Use == for equality, != for inequality, and <, >, <=, or >= for ordered comparisons. 3 == 3 is TRUE; 3 != 3 is FALSE. A single = names an argument or performs assignment, so it is not an equality test.
Combine elementwise conditions with & for “and,” | for “or,” and ! for “not.” 5 > 3 & 2 > 4 is FALSE: both parts must be true for “and.”
Most decimals have tiny binary storage errors. In R, 0.1 + 0.2 == 0.3 is FALSE. A tolerance-based test, isTRUE(all.equal(0.1 + 0.2, 0.3)), is TRUE; dplyr::near() offers a similar test.
Some calculations return special values: 1 / 0 is Inf, and 0 / 0 is NaN (“not a number”). NA means missing. NA + 1 is NA, because an unknown input leaves the sum unknown.
Key Takeaways
- Parentheses control calculation order;
%/%and%%bind more tightly than*and/. - Powers group right to left, and
-2^2differs from(-2)^2. log()is natural log;round()sends exact halves to the even digit.- R code uses a decimal point; commas separate arguments.
- Compare with
==, combine conditions with&or|, and negate with!. - Use a tolerance to compare computed decimals; distinguish
NA,NaN, andInf.
2Create objects and call functions
Named objects let a calculation grow beyond one line. You can keep inputs, build intermediate results, and inspect a result before using it again. Functions perform named operations on these values, with arguments controlling their behavior. The order of assignments and the distinction between displaying and saving a result matter whenever you change an input or rerun part of an analysis.
2.1 Store values under useful names
An object stores a value under a name in R's memory. A name lets you use the same value in later steps without typing it again. Create the object before running code that needs it.
Assign, inspect, and replace
The assignment operator <- can be read as “gets.” Run height_cm <- 172: the object height_cm gets the value 172. Assignment normally prints nothing. Type height_cm to inspect the value, or wrap an assignment in parentheses to assign and print together: (height_cm <- 172).
The Environment pane shows objects in the current session. ls() lists ordinary object names in the console, and rm(height_cm) removes this object. Removing an object does not remove the script line that created it; you can rerun that line.
Assigning to an existing name replaces its value without a warning. After x <- 3 followed by x <- 4, x holds 4. Use a different name when you need to keep the original value for comparison.
Build a calculation in order
Suppose height is 172 cm and mass is 68 kg. Convert height to meters before calculating body mass index:
height_cm <- 172
weight_kg <- 68
height_m <- height_cm / 100
bmi <- weight_kg / height_m^2
bmi
The steps create 1.72 m and then a BMI of about 22.9854. round(bmi, 1) returns 23. The names show the units of the inputs and make it easier to follow which value each line uses.
Now run weight_kg <- 70. The stored bmi is still about 22.9854. R saved the result of the earlier calculation; it did not create a live spreadsheet formula. Rerun bmi <- weight_kg / height_m^2 to calculate from the new mass. If a changed input feeds several later steps, rerun all of those steps in order.
Choose valid names
Names can contain letters, digits, dots, and underscores. They must start with a letter or with a dot that is not followed by a digit. They cannot contain spaces or be reserved words such as TRUE, NA, if, or function. For ordinary analysis code, lowercase names with underscores are easy to read.
| Valid name | Invalid name | Reason for rejection |
|---|---|---|
temp_c | temp c | Contains a space |
temp2 | 2temp | Starts with a digit |
mean_height | _height | Starts with an underscore |
Names are case-sensitive: Height and height are different. An “object not found” error may mean a typo, the wrong case, or a creation line that has not run. Tab completion helps keep names consistent.
Keep assignment distinct from comparison
Use <- for assignment and = for naming function arguments. Alt+- / Option+- inserts the assignment operator in RStudio. Spaces can change the meaning here: x <- 3 assigns 3, while x < -3 tests whether x is less than negative 3.
Objects belong to the running session. R can save and restore them through .RData, but a saved script records how they were made. With workspace restoration and saving switched off, a new session starts without those analysis objects and rerunning the script rebuilds them.
Key Takeaways
name <- valuecreates or replaces an object; assignment normally prints nothing.- Derived objects keep their calculated values until you rerun their assignment lines.
- Names are case-sensitive and must follow R naming rules.
ls()lists ordinary object names, andrm()removes named objects.- A saved script preserves the steps needed to recreate session objects.
2.2 Give functions the inputs they need
A function is named code that takes inputs and returns a result. Its inputs are arguments. Calling a function means writing its name followed by parentheses, with commas between arguments.
Read a call
In round(3.14159, digits = 2), the main input is 3.14159 and the digits argument requests two decimal places. The result is 3.14. Write the function name directly next to the opening parenthesis.
Arguments can match by position or by name. These calls all produce 1, 4, 7, and 10:
seq(1, 10, 3)
seq(from = 1, to = 10, by = 3)
seq(by = 3, to = 10, from = 1)
The first call depends on the expected argument order. The others label the inputs, so their order is clear even when rearranged. A useful style is to leave the main input unnamed and name settings such as digits = 2 or by = 3.
Many arguments have defaults, which R uses when you leave them out. args(round) shows a default of digits = 0, so round(3.7) returns 4. The function's help page explains its arguments and defaults. Leaving a setting out means accepting that setting's default.
Handle a missing input
A mean uses all supplied values, but NA represents an unknown value. Therefore mean(c(2, 4, NA)) returns NA. To calculate the mean of the known observations, set na.rm = TRUE:
mean(c(2, 4, NA), na.rm = TRUE)
R calculates from 2 and 4 and returns 3. The call changes which observations the summary uses; it does not fill in the missing observation. sum(), median(), min(), and max() also support na.rm. The setting belongs inside the call, separated from the data argument by a comma.
Follow nested calls from inside out
In round(sqrt(10), 2), R calculates sqrt(10) first and passes that value to round(). The final result is 3.16. You can make the same stages visible with objects:
root <- sqrt(10)
root_rounded <- round(root, digits = 2)
The second line stores a new rounded result. Calling round(root, 2) without assignment displays the rounded value but leaves root at its original precision. Ordinary calculation functions do not rewrite the input object just because you display their result.
Distinguish text, names, and functions
Quoted text is a value: toupper("hello") returns "HELLO". Unquoted hello is treated as an object name, so it must exist before you can use it. Both straight single and double quotes work for strings; use double quotes consistently.
Typing mean without parentheses displays the function itself. Typing mean(c(2, 4)) calls it and returns 3. Missing commas or parentheses prevent R from reading the call: round(3.14159 2) lacks the comma between inputs.
Functions such as round() and c() are available in base R. Other functions come from installed packages. Attach a package with library() to use its exported functions by name, or name the package explicitly with package::function().
Key Takeaways
- A call supplies arguments inside parentheses, separated by commas.
- Names identify arguments explicitly; unnamed inputs depend on position.
- An omitted optional argument uses its default.
na.rm = TRUEcalculates a summary after excluding missing inputs.- Nested calls run inside out; assign a returned result if you need to keep it.
- Quoted text is a value, while unquoted text names an object.
3Work with vectors and data types
R works naturally with collections of values. A vector might hold temperatures, distances, or a row of logical tests. Its type controls which operations it supports, and its order controls how values line up with another vector. Building and inspecting vectors prepares you to recognize conversions, calculate across observations, and select exactly the values you need without writing a separate command for each one.
3.1 Build vectors and inspect their types
A vector is an ordered collection of values. An atomic vector holds one storage type, and even a single number is a vector of length 1. Data columns often start as vectors, so their types determine which calculations make sense.
Combine, sequence, and repeat
c() combines values. For four temperatures in degrees Celsius, write:
temps <- c(18.5, 21.0, 19.2, 23.4)
length(temps)
The length is 4. Values keep their order: the second element is 21.0. Use 1:5 to build consecutive integers. For another step size, seq(0, 1, by = 0.25) gives 0, 0.25, 0.50, 0.75, and 1.
rep() repeats values. rep(c("x", "y"), times = 2) repeats the entire pair, giving "x" "y" "x" "y". With each = 2, it repeats each value before moving on: "x" "x" "y" "y". The argument name changes the pattern, even though both results have length 4.
Recognize the main types
| Type | Example | Meaning |
|---|---|---|
| Logical | TRUE | A true/false value |
| Integer | 5L | A whole number stored as an integer |
| Double | 5 or 2.5 | A number stored with floating-point precision |
| Character | "five" | Text |
Integer and double are both numeric. R also has complex and raw types. typeof(5) returns "double": a whole-looking number typed without L is still stored as a double. typeof(5L) returns "integer", and 1:3 also creates integers. class(5) returns "numeric"; class and storage type answer different questions.
Use typeof() to inspect storage, or tests such as is.numeric(), is.character(), and is.logical() for a true/false answer. is.numeric(5L) is TRUE because integers are numeric too.
Quotes matter: "5" is character data. Trying "5" + 1 produces an error about a non-numeric argument. Write logical constants as TRUE and FALSE, without quotes. "TRUE" is text. Avoid the abbreviations T and F, which are ordinary names someone could overwrite.
Recognize missing values
NA marks a missing observation. c(1, NA, 3) is a numeric vector with one unknown element. Test with is.na():
is.na(c(1, NA, 3))
The result is FALSE TRUE FALSE. Testing c(1, NA, 3) == NA instead returns NA NA NA: equality with an unknown value is itself unknown.
See how vectors fit into tables
A data frame is a table whose columns have equal lengths. Ordinary atomic columns each have one type; different columns can have different types. A tibble is a modern form of data frame. str() or dplyr::glimpse() shows the structure and column types; common tibble labels are <lgl>, <int>, <dbl>, and <chr>.
A list can hold different types and lengths together. For example, list(172, "cm", TRUE) keeps a number, text, and a logical value as separate components. Combining atomic values with c() instead requires R to choose one common type.
Key Takeaways
c()builds a vector;length()reports its number of elements.- Use
:,seq(), andrep()for regular sequences and repetition. - Logical, integer, double, and character are the main atomic types; integer and double are numeric.
typeof(5)is"double", whiletypeof(5L)is"integer".- Use
is.na()to locate missing values. - Tables can have columns of different types; lists can hold components of different types and lengths.
3.2 Control how R converts values
When you combine values of different types into an atomic vector, R must store them in one common type. This automatic conversion is coercion. It can change what calculations are possible without changing how familiar the values look.
Predict the common type
For the four main types, the conversion order is logical → integer → double → character. The most flexible type present wins. c(TRUE, FALSE, 1L) becomes the integers 1, 0, and 1. c(TRUE, 2.5) becomes the doubles 1 and 2.5. c(1, "2", 3) becomes the text values "1" "2" "3".
c() does this silently. A single text value can turn an intended numeric vector into character data. mean(c("12.5", "13")) returns NA with a warning that its argument is not numeric or logical. A quoted value such as "12,5" also needs attention: R code uses a decimal point, not a comma.
Convert explicitly and inspect failures
Use as.numeric(), as.integer(), as.character(), or as.logical() when you intend to change type. For example:
raw_values <- c("3.5", "7", "abc")
values <- as.numeric(raw_values)
values
is.na(values)
The conversion produces 3.5, 7, and NA, with the warning NAs introduced by coercion. The missingness test returns FALSE FALSE TRUE, locating the failed conversion. Compare that position with raw_values: "abc" cannot be read as a number. Inspect and correct the input; removing all missing values could hide the failed conversion.
as.integer() truncates toward zero. as.integer(3.9) is 3 and as.integer(-3.9) is -3. If you need the nearest whole number, round first: as.integer(round(3.9)) is 4.
Calculate with logical values
In numeric calculations, TRUE becomes 1 and FALSE becomes 0. A sum counts true conditions; a mean gives their proportion. With scores of 55, 72, 48, 90, and 66:
scores <- c(55, 72, 48, 90, 66)
passed <- scores >= 60
sum(passed)
mean(passed)
The comparison gives FALSE TRUE FALSE TRUE TRUE. There are three true values, so the count is 3 and the proportion is 0.6, or 60%. Missing values need the same attention here as in other summaries.
The reverse conversion maps 0 to FALSE and any other non-missing number to TRUE. Thus as.logical(c(0, 2, -1)) gives FALSE TRUE TRUE. Supported text spellings include "TRUE", "true", and "FALSE"; as.logical("yes") gives NA.
Compare numbers as numbers
Character comparisons follow text ordering. "10" < "9" is TRUE because the initial character "1" comes before "9". After numeric conversion, as.numeric("10") < 9 is FALSE. When a numeric calculation or comparison behaves unexpectedly, inspect typeof(x) before changing the formula.
Key Takeaways
- Mixed atomic values convert to one common type: logical → integer → double → character.
- Explicit conversions can introduce
NA; inspect the original values when a warning appears. as.integer()truncates toward zero; useround()when rounding is intended.- Logical sums count true values, and logical means give their proportion.
- Character comparisons use text order, so numeric-looking text may need conversion.
3.3 Calculate and select by element
Many R operations are vectorized: they work on all elements at once. The position of each element matters when vectors are combined or when you select values.
Calculate element by element
With temps_c <- c(18.5, 21.0, 19.2, 23.4), temps_c + 273.15 converts every value to kelvin, returning 291.65, 294.15, 292.35, and 296.55. You do not need a separate command for each temperature.
Two equal-length vectors combine by matching positions:
distance_km <- c(12, 30, 8)
time_h <- c(0.5, 1.5, 0.25)
distance_km / time_h
The three speeds are 24, 20, and 32 km/h. R pairs the first distance with the first time, then the second with the second. Check that the observations have the same order.
A summary function instead reduces several inputs to one result. For x <- c(4, 8, 15, 16, 23, 42), sum(x) is 108, mean(x) is 18, median(x) is 15.5, max(x) is 42, and length(x) is 6. In contrast, sqrt(x) returns six square roots.
Check recycling
Base R repeats the shorter vector when lengths differ. c(1, 2, 3, 4) + c(10, 20) reuses 10 and 20 as 10, 20, 10, 20, producing 11, 22, 13, 24. A length-one value repeats at every position, which explains the temperature conversion.
If the longer length is not a multiple of the shorter, base R still calculates but warns. c(1, 2, 3) + c(10, 20) produces 11, 22, 13 and longer object length is not a multiple of shorter object length. A result without a warning can still pair the wrong observations, so compare lengths and meaning.
Tibble columns use stricter rules: they must have compatible sizes, with length-one inputs recycled. tibble::tibble(a = 1:3, b = 0) repeats zero across three rows. A column of length 2 cannot fill four rows this way; that construction errors.
Select positions
R indexes from 1. For the six-value x above:
x[1]returns 4.x[c(2, 4)]returns 8 and 16.x[2:4]returns 8, 15, and 16.x[7]returnsNA, andx[0]returnsnumeric(0), an empty vector.
Negative indices omit positions. x[-1] drops the first value, and x[-c(1, 2)] drops the first two. Do not mix positive and negative positions in one index: x[c(-1, 2)] errors.
Select by a condition
x > 15 produces a logical vector, with TRUE in the positions you want. Use it inside the index: x[x > 15] returns 16, 23, and 42. To keep values above 5 and below 20, write x[x > 5 & x < 20], returning 8, 15, and 16.
%in% tests membership: c(4, 9, 15) %in% x gives TRUE FALSE TRUE. Unlike ==, it looks anywhere in the set on the right instead of comparing matched positions.
You can assign to selected positions. After y <- x and y[2] <- 10, only the second element of y changes. The ordinary numeric vector x keeps its original values.
Key Takeaways
- Equal-length vectors calculate position by position; summaries reduce many values to one.
- Base R recycles shorter vectors and warns when lengths do not divide evenly.
- Tibble construction recycles length-one inputs, not arbitrary shorter columns.
- Indices start at 1; positive indices keep positions and negative indices omit them.
- Logical indexing keeps positions marked
TRUE;%in%tests membership. - Assigning to part of a copied numeric vector changes the copy.
4Extend R with packages and the tidyverse
Packages extend R with tools for reading, transforming, and presenting data. Getting a package onto your computer and making its functions available in a session are separate steps. The tidyverse brings related packages together, while explicit package names help resolve shared function names. A pipeline makes a chain of calls readable in the order the results move through them.
4.1 Install a package and make it available
A package bundles functions, data, and documentation that extend R. Base R already supplies tools such as mean() and round(). CRAN provides thousands of additional packages; Bioconductor and GitHub are other sources.
Separate installation from session use
Installation downloads a package into a package library, a folder on your computer. Run this in the console:
install.packages("tidyverse")
The package name is text, so it goes in quotes. You install a package once for the R library you are using, and install it again when needed after an R upgrade. Reinstalling it every time you analyze data is unnecessary.
To make the installed package's functions available by name, attach it in the current session:
library(tidyverse)
Think of installation as putting a reference book on a shelf. Attaching the package is opening the book for the current work session. Restarting R leaves the book on the shelf but closes it. Put library() calls at the top of scripts so another reader can see which packages the analysis needs.
Installing alone does not attach a package, and library() cannot install one that is missing. Keep install.packages() in the console: running an analysis script should not reinstall software or change another person's package library.
Diagnose the right stage
An error containing “there is no package called” means R could not find that installed package under the supplied name. Check spelling and case before installing. tidyverse and Tidyverse are different names.
An error containing “could not find function” means the function name is unavailable. Check the spelling and whether its package has been attached. For example, after installing ggplot2, a new session still needs library(ggplot2) before a plain ggplot() call is available.
Startup information printed by library() is a message, not evidence that loading failed. Read its content before treating colored text as an error.
Name the package directly
The double colon lets you call an exported function from an installed package:
dplyr::near(0.1 + 0.2, 0.3)
This returns TRUE. R loads the package's namespace in the background but does not attach its other functions for bare-name calls. The syntax says exactly which package supplies the function and works without an earlier library(dplyr). It still requires dplyr to be installed.
Check versions and updates
RStudio's Packages tab lists installed packages and indicates attached packages with check marks. packageVersion("dplyr") reports the installed version. update.packages() or the Packages tab's Update button updates installed packages; restart R afterward to use the new versions in a clean session.
R normally uses separate package libraries for different minor R versions. Moving from one minor version to another can therefore require reinstalling the packages you use. If a previously working package is suddenly unavailable after an upgrade, check which R version and library the new session is using.
Key Takeaways
- Install into a package library once; attach with
library()in each new session. - Keep installation commands in the console and
library()calls at the top of analysis scripts. package::function()selects a function without attaching the package.- Check package names and versions; restart R after updates.
4.2 Chain steps and resolve function conflicts
The tidyverse is a collection of data-science packages designed to work together. Installing its meta-package installs the collection; library(tidyverse) attaches the nine core packages in one step.
Know where to look
| Package | Main job |
|---|---|
| ggplot2 | Graphs |
| dplyr | Data transformation |
| tidyr | Data tidying |
| readr | Reading rectangular files |
| tibble | Modern data frames |
| stringr | Working with text |
| forcats | Working with factors |
| lubridate | Dates and times |
| purrr | Applying functions over inputs |
Lubridate joined the attached core in tidyverse 2.0.0 in 2023. You can read the startup message to see which packages were attached and their versions.
A tibble is the tidyverse's form of data frame. It prints dimensions, column types, and a limited view of the rows and columns. For a long table, the default display shows the first 10 rows and columns that fit; the rest of the data remains stored. tibble::as_tibble(mtcars) converts a built-in data frame. Type labels such as <dbl> and <chr> help you spot numeric and text columns.
Resolve names shared by packages
Two packages can export functions with the same name. This is masking: with ordinary package attachments, the most recently attached definition takes priority. After attaching the tidyverse, its startup message reports that dplyr::filter() masks stats::filter() and dplyr::lag() masks stats::lag(). The message reports a naming conflict; it is not an error.
For reliable selection, name the package: dplyr::filter() or stats::filter(). Loading MASS after dplyr can make bare select() call MASS's function. Then select(mtcars, mpg) fails with an unused-argument error. dplyr::select(mtcars, mpg) chooses the intended function regardless of attachment order.
The conflicted package makes ambiguous calls errors until you choose a function. With it attached, conflicts_prefer(dplyr::filter) declares your preference. This makes a choice explicit instead of leaving it to load order.
Read a pipeline from left to right
The native pipe |> passes its left-hand result into the first argument of the call on the right. x |> mean() means mean(x). x |> round(1) means round(x, 1): the piped value fills the first argument, and 1 supplies digits.
Follow this pipeline one stage at a time:
c(18.5, 21.0, 19.2) |>
mean() |>
round(1)
The vector has three values. mean() reduces it to about 19.56667. round(1) rounds that one mean to 19.6. The equivalent nested form is round(mean(c(18.5, 21.0, 19.2)), 1).
The native pipe is part of R since 4.1.0. Older tidyverse code often uses %>%, supplied by magrittr and available with the tidyverse. Both handle these everyday chains. Base R functions such as mean() work in a native pipeline without loading the tidyverse.
Ctrl+Shift+M / Cmd+Shift+M inserts a pipe in RStudio. Under Tools > Global Options > Code, select “Use native pipe operator, |>” to make that shortcut insert the native form.
Key Takeaways
- The tidyverse meta-package attaches nine core packages with shared data-science conventions.
- A tibble prints a preview with dimensions and types; unprinted rows remain stored.
- Masking changes which same-named function a bare call reaches.
package::function()makes the intended function explicit.|>passes a result to the next call as its first argument.
5Organize reproducible work in scripts and projects
A reproducible analysis needs a reliable path from its starting data to its results. Saved scripts record that path, projects keep the files together, and relative paths let another computer find them. Consistent names, comments, and layout make the steps easier to inspect. A fresh-session run then checks whether the saved code contains everything the analysis needs.
5.1 Save an analysis as a runnable script
A script is a plain-text file ending in .R that records code in its running order. It lets you edit a step, rerun an analysis, or hand the steps to another person. Objects in memory hold results; the script preserves how to make them.
Write and run code
Open File > New File > R Script, or press Ctrl+Shift+N / Cmd+Shift+N. Write code in the source editor. Ctrl+Enter / Cmd+Enter runs the current expression or selected code in the console; an expression can span several lines. The cursor then moves to the next expression. The Run button also sends code to R.
Ctrl+Shift+S / Cmd+Shift+S sources the whole script, running it from top to bottom. The Source button does the same. Arrange the script in dependency order: attach packages, read or create data, and then calculate results.
# Compare the measured heights ----
height_cm <- c(168, 175, 181)
mean_height_cm <- mean(height_cm)
mean_height_cm
The vector is created before mean() needs it. Putting the mean calculation first might seem to work if height_cm already exists from earlier console work. In a new empty session it fails, revealing the missing order.
Explain decisions with comments
Outside quoted text, # starts a comment that runs to the end of the line. Inside "a # b", it is part of the string. Use comments to explain reasons, such as # Exclude the test run from day 1, when that decision would not be clear from the code.
A comment ending in four or more dashes, such as # Load data ----, creates a section in RStudio's script outline. Ctrl+Shift+R / Cmd+Shift+R inserts a section. This makes a long script easier to navigate.
RStudio also checks code while you type. A red cross in the margin signals a syntax problem; a yellow warning marks a possible issue. Hover over it to read the detail. A missing closing parenthesis needs a code correction, not a new package installation.
Save with a useful name
Save using Ctrl+S / Cmd+S. An asterisk marks unsaved changes. Choose names that describe the work, avoid spaces, and sort in the intended order: 01-import.R, 02-clean.R, and 03-plots.R. Zero-padding keeps later numbered files in order. Dates such as 2026-03-15 sort by year, month, and day.
Keep interactive inspection and setup in the console: View(), package installation, and a personal setwd() path do not belong in a reusable analysis script. rm(list = ls()) removes ordinary objects but leaves attached packages and session settings; it is not equivalent to restarting R.
Check the script from a fresh session
Disable workspace restoration and saving in RStudio's options so hidden objects do not return. Then use Session > Restart R, or Ctrl+Shift+F10 / Cmd+Shift+0, and source the script. Check both that it runs and that its results agree with what you expect. If it only works after commands typed separately in the console, move those necessary steps into their proper place in the script.
Key Takeaways
- A script stores the ordered code needed to recreate an analysis.
- Run an expression with Ctrl+Enter / Cmd+Enter, or source the whole script.
- Comments explain decisions; section comments organize longer scripts.
- Save descriptive, sortable file names.
- Restart without restored objects, then source to detect hidden dependencies.
5.2 Keep files together in a project
A working directory is the folder R starts from when resolving a relative file path. A project gives one analysis a clear home, with its code, input data, and outputs kept together.
Locate a file from the working directory
getwd() prints the current working directory, also shown at the top of RStudio's console. If the directory is the heat-study folder, "data/temps.csv" points to temps.csv inside that folder's data subfolder.
An absolute path starts from the top of a drive, such as "C:/Users/amira/Documents/heat-study/data/temps.csv" or "/Users/amira/heat-study/data/temps.csv". It works wherever that exact location exists. A relative path starts from the working directory. It can survive moving the project because it describes the file's position inside the project.
The relative path works after a move when the internal folder structure stays the same and R starts from the project folder. Opening a script alone does not establish that starting folder. If R reports a missing file, check getwd(), the subfolder, and the exact file name before editing the analysis.
Open the project first
Choose File > New Project to create a project in a new or existing folder. RStudio creates a .Rproj file. Open that file through File > Open Project or by double-clicking it. RStudio sets the working directory to its folder and reopens your project files.
For example, keep these files together:
heat-study/
heat-study.Rproj
01-import.R
02-plots.R
data/
temps.csv
figures/
The input path is "data/temps.csv"; an output could be "figures/daily-temps.png". A call such as readr::read_csv("data/temps.csv") finds its input relative to the project root. Opening the project gives a colleague the same starting point without needing your personal home-directory path.
Use one project for each analysis. Avoid a script line such as setwd("C:/Users/amira/..."), which depends on a personal location. The project establishes the working directory before the script runs.
Write paths safely in R strings
Use forward slashes on Windows, macOS, and Linux. A backslash begins an escape sequence in an R string. To represent one literal backslash, you need two, as in "C:\\Users\\amira". Forward slashes make the same path easier to read: "C:/Users/amira". A leading ~ stands for your home folder.
Rebuild objects from code
In Tools > Global Options > General, clear “Restore .RData into workspace at startup” and set “Save workspace to .RData on exit” to “Never.” Check project settings too if they override the defaults. Restored objects can make incomplete scripts appear to work; an empty start makes missing steps visible.
Keep raw data unchanged. Read from data/, then save derived tables and figures to separate files in output/ or figures/. If a cleaning step is wrong, you can correct its code and rerun from the original input without losing the original observations.
Key Takeaways
getwd()identifies the starting folder for relative paths.- Opening a
.Rprojfile sets the working directory to the project folder. - Relative paths remain portable when the project structure and starting directory are preserved.
- Use forward slashes in R paths on every operating system.
- Disable workspace saving/restoration and preserve raw inputs separately from outputs.
5.3 Make code easy to read
Code style makes names, spacing, and layout predictable. Consistent formatting helps you see the structure of a calculation and review changes. The tidyverse style guide supplies the conventions used here.
Use names that explain the values
Choose lowercase snake_case names, with words separated by underscores. daily_rain_mm says more than x, and the unit helps distinguish millimeters from another measurement. Prefer mean_height_cm to mixing forms such as MeanHeight and mean.height.
Avoid reusing common function or constant names such as mean, c, and T. A familiar name already has a meaning to other R readers. Teams may use other conventions, such as Google's BigCamelCase for function names; follow the project's chosen style consistently.
Space the code by its structure
Put spaces around <-, argument =, comparisons, and arithmetic operators such as +, -, *, and /. Put a space after a comma, not before it. Keep the function name beside its opening parenthesis. Do not add spaces around ^, :, or ::.
For example, write:
avg <- mean(rain_mm, na.rm = TRUE) * 2
positions <- 1:5
squared <- positions^2
The names and spaces make the assignment, arguments, and calculation visible without changing the result. They also help distinguish x <- 3 from x < -3, where moving the space changes assignment into a comparison.
Give long calls room
Aim for lines of about 80 characters. When a call becomes hard to scan, put arguments on separate indented lines:
seq(
from = 0,
to = 20,
by = 2
)
RStudio can show a margin under Tools > Global Options > Code > Display > Show margin. The guide is a reading aid; you do not need to break a short, clear call across lines.
For a pipeline, end the line with |> and indent each next step by two spaces:
temps_c |>
mean() |>
round(1)
Each line shows one operation. The pipe at the end signals that the expression continues. Graph code using ggplot2 layers uses a similar line-ending layout with +.
Start comments with # and a space. A comment should explain a decision such as why a test run is excluded. Section comments ending in dashes create navigation points when the script grows.
Let a tool handle formatting
In RStudio, Ctrl+Shift+A / Cmd+Shift+A reformats selected code. The styler package can format an entire file with styler::style_file("01-import.R"), or its “Style active file” addin. Air is another formatter and can be configured to run when you save in RStudio or Positron.
The lintr package reports style problems without rewriting the code. A formatter changes layout; a linter points out issues to review. Neither checks that your data, units, or chosen calculation answer the question you intended.
Key Takeaways
- Use descriptive
snake_casenames and a consistent project style. - Space operators and commas consistently, keeping
^,:, and::tight. - Break long calls by argument and pipelines by step.
- Formatters rewrite layout; lintr reports issues for review.
6Find help and solve problems
Help pages and error messages are part of everyday work in R. A useful help page explains an argument or shows a small example; a useful diagnosis locates the first failing step and inspects its inputs. When you need another person to help, a reproducible example makes the problem runnable. These habits let you turn unfamiliar behavior into a concrete question you can investigate.
6.1 Read help and find a useful example
R's documentation explains what a function accepts and returns. Start with the function you are using, then move to longer guides when you need to see several functions working together.
Open the right help page
?round and help("round") open the same page. In RStudio, F1 opens help for the function under the cursor. For a package function, ?dplyr::filter names the package explicitly. For an operator, quote the name: help("%%").
A help page has sections with different jobs:
- Description tells you what the function does.
- Usage shows the call and argument defaults.
- Arguments explains the inputs and settings.
- Details gives behavior that needs more explanation.
- Value describes the returned result.
- See Also points to related functions.
- Examples gives runnable code.
Usage is especially useful when a call runs but returns an unexpected result. It lets you check whether an omitted setting has a default you did not intend.
Find a missing-value setting
Suppose median(c(3, NA, 7, 1)) gives NA. Open ?median. Its usage includes na.rm = FALSE, which keeps missing values by default. Set it to true:
median(c(3, NA, 7, 1), na.rm = TRUE)
The known values are 1, 3, and 7, so the result is 3. The help page tells you how to ask for this behavior. It does not turn the missing value into a measured value.
Run individual lines from Examples, or use example(round) to run the documented rounding examples. A small example lets you see a function's behavior before combining it with a larger analysis.
Search when the name is unknown
??"standard deviation" searches installed help, through help.search(). apropos("mean") searches names of loaded objects, including user-created objects. Add mode = "function" if you only want function names. These searches have different scopes: a package may be installed without its names being available in the current session.
For web searches, include R and the action you need, for example “R standard deviation of a column.” A package's own reference site is useful once you know which package is involved.
Use longer guides for a workflow
A vignette is a package guide with connected examples. browseVignettes("dplyr") lists dplyr's installed vignettes; vignette("dplyr") opens its introduction. Package websites provide reference pages and articles. Posit's cheatsheets offer compact reminders, and R for Data Science, second edition, provides longer explanations online.
AI assistants can draft code or explain an unfamiliar call. Check each suggested function and argument against its documentation, run the code, and test it with a small input whose answer you know. A convincing explanation alone cannot establish that the named function exists or that the code performs the intended calculation.
Key Takeaways
?name,help(), and F1 open function documentation.- Usage and Arguments identify defaults; Value explains the returned object.
- Run Examples to see behavior on small inputs.
- Help search, name search, vignettes, and package websites serve different needs.
- Check suggested code against documentation and a small known-answer example.
6.2 Trace a problem and share a reproducible example
An R problem becomes easier to solve when you identify the failing step and make it small enough to inspect. Read the condition's words, then examine the input at that step.
Tell errors, warnings, and messages apart
An error stops the affected code. A warning reports a possible problem even though evaluation continued. A message provides information, such as which packages were attached. RStudio often shows all three in red. Read the words to identify the condition.
For round("3.7"), an error identifies round() and says “non-numeric argument to mathematical function.” The quotes made the input text. Inspecting typeof("3.7") confirms character data; using a numeric input addresses the cause.
Common messages point toward different checks:
| Reported problem | First checks |
|---|---|
| “object ... not found” | Spelling, case, and the creation line |
| “could not find function” | Function spelling and package attachment |
| “there is no package called” | Package spelling and installation |
| “unexpected symbol” or “unexpected ')'” | Commas, operators, and matching parentheses |
| “non-numeric argument to binary operator” | Whether an arithmetic input is text |
A coercion warning such as NAs introduced by coercion deserves inspection even if R produced a result. A failed text-to-number conversion can introduce missing values that affect later summaries.
Follow the first failure
Fix the first error before later ones: a failed object creation can cause several later “not found” errors. Run lines in order and inspect intermediate objects using print(), str(), or typeof(). Restart R and rerun the saved script to expose reliance on old session objects.
For searching, copy the general part of the error and add R and the package name. Omit personal object names that make the search needlessly specific. Relevant places include package documentation, Posit Community, Stack Overflow questions tagged r, and package GitHub issues. Sys.setenv(LANGUAGE = "en") requests English messages for the session when translated messages make searching difficult.
Make the problem runnable elsewhere
A reproducible example, or reprex, contains the smallest self-contained code that still shows the problem. Include required library() calls, a small data set, the failing call, the actual output, and what you expected. For example:
x <- c(2, 4, NA)
mean(x)
The actual result is NA; the intended mean of the known values is 3. This example exposes the missing-value issue without requiring anyone else's files. dput(x) prints R code that recreates the object, while dput(head(my_data)) can capture the first six rows of a table.
Copy the example code and run reprex::reprex(). The package runs it in a fresh R session and prepares code plus output for sharing. A dependency that existed only in your current session becomes visible. reprex::reprex(session_info = TRUE) includes version information; sessionInfo() also reports the R and package environment.
Key Takeaways
- Errors stop code; warnings flag possible problems; messages provide information.
- Fix the first failure and inspect the objects that reach it.
- Search the general error text with R and the relevant package.
- A reprex includes runnable setup, small data, the failing call, and actual versus expected results.
- Use
dput()to recreate data and reprex to test the example in a fresh session.
R and RStudio examples
1Run and understand your first commands
12 steps
- 1IntroductionStart with a visible exchange
You will enter a short command, read what R returns, and then build a calculation that tests a condition. R does the computing; RStudio gives you the editor, console, and panes around it.
The first useful habit is to distinguish what you type from the prompts and position labels R prints. That makes the console a place where you can check an idea one expression at a time.
- 2ExplanationFind where code runs
Install R before RStudio Desktop, then open RStudio. The source editor holds saved code; the console runs commands. The Environment pane shows session objects, while the other pane offers Files, Plots, Packages, and Help tabs.
These are the default pane groups, and you can rearrange them. With a new script open, the usual layout places the source editor above the console on the left.
- 3ExampleRead a result without its position label
At the
>prompt, type2 + 6and press Enter. R displays:[1] 8The result is 8. The
[1]identifies the first value’s position on that output line. It is not another number in the answer. A long vector may wrap onto more lines, each labeled with the position of its first value. - 4TipRecover from an unfinished command
Type
sqrt(36without a closing parenthesis. The console changes to a leading+: R is waiting for the rest of the expression.Type
)and press Enter to finish the call, or press Esc to cancel it. Adding another command while a quote or parenthesis remains open often makes the input more confusing. The prompt tells you whether R is ready to start something new. - 5ChallengeExplain the console state
After entering
round(7.38, 1, you see a+prompt. What should you type to finish the calculation, and what result should appear?---reveal---
Type
)to close the call. R returns[1] 7.4. The leading+was a continuation prompt, and[1]labels the output position. Neither is part of the numeric result. - 6ExplanationLet the operators determine the order
R uses
*for multiplication and^for powers. In2 + 3 * 4, it multiplies first, giving 14. Parentheses change the grouping:(2 + 3) * 4gives 20.The order among these arithmetic groups is powers, then
%/%and%%, then multiplication/division, then addition/subtraction. Use parentheses when the intended grouping would otherwise be easy to misread. - 7ExampleCalculate with a measurement
A walker travels 9 km in 2 hours. Enter:
9 / 2R returns 4.5, so the average speed is 4.5 km/h. To express it in meters per second, write
4.5 * 1000 / 3600, which gives 1.25. The conversion uses 1000 meters per kilometer and 3600 seconds per hour; keeping those factors visible shows how the units change. - 8Key InsightKeep a negative base inside parentheses
A power binds more tightly than a leading minus.
-3^2means the negative of3^2, giving -9. In(-3)^2, the entire negative number is the base, so the result is 9.Powers also group from the right:
2^3^2means2^(3^2). Multiplication and division instead group from the left, so24 / 3 / 2is 4. - 9ExampleUse a call to round a calculation
round(9 / 2, digits = 1)first divides, then rounds to one decimal place, returning 4.5. Commas separate arguments: the first is the value and the second is the setting.In particular,
round(4,5)rounds 4 to five decimal places; it does not mean 4.5. For exact halves, R rounds to even:round(4.5)gives 4 andround(5.5)gives 6. - 10ConnectionTurn a result into a test
Comparisons produce logical values.
4.5 > 4isTRUE, while4.5 == 4isFALSE. Combine tests with&when both must hold, or|when either is enough.Computed decimals may carry tiny binary errors. Use a tolerance-based comparison such as
isTRUE(all.equal(0.1 + 0.2, 0.3))when that small numerical difference should be accepted. - 11ChallengeTrace a complete condition
What logical result does
(3 + 5) / 2 >= 4 & 13 %% 4 == 1return?---reveal---
The parenthesized sum is 8, and dividing by 2 gives 4, so the first condition is true. The remainder of 13 divided by 4 is 1, so the second is true too.
&requires both, and the result isTRUE. At the console, a new>prompt means R is ready for the next command. - 12RecapKeep three checks beside the console
Before running an expression, check that R is at a ready prompt and the call is complete. Before trusting a numeric result, check the grouping and units. Before using a logical result, check the comparison and whether both or either condition should hold.
Use the console for quick experiments and keep the working calculation in a script so that its inputs and order are available next time.
2Build a calculation with named inputs
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild a short chain of results
- 2ExplanationStore the starting values
- 3ExampleCreate the first dependent value
- 4ExampleChange one input
- 5ChallengeFind the value that stayed behind
- 6ExplanationIdentify an argument and a default
- 7ExampleName inputs to remove positional doubt
- 8ExampleHandle a missing observation
- 9ChallengeKeep the setting in the right call
- 10Key InsightDisplaying is different from replacing
- 11TipDistinguish text from a name
- 12ChallengeFollow creation, calculation, and storage
- 13RecapInspect the chain in running order
3Build, convert, and select observations
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionWatch values and their structure
- 2ExplanationBuild a vector in observation order
- 3ExampleInspect what a number is made of
- 4TipChoose a sequence or repetition pattern
- 5ChallengeChoose the missing-value test
- 6ExplanationPredict a shared type
- 7ExampleLocate a failed conversion
- 8Key InsightA logical mean is a proportion
- 9ChallengeConvert before choosing a comparison
- 10ExplanationMatch observations by position
- 11ExampleRepeat one value or a short pattern
- 12TipTreat a length warning as a pairing check
- 13ExampleKeep or omit positions
- 14ExampleUse a condition as the index
- 15ConnectionTest membership and change a copy
- 16ChallengeTrace a changed vector into a summary
- 17RecapInspect before you summarize
4Use a package and follow a pipeline
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow a tool from disk into a calculation
- 2AnalogyPut a book on the shelf
- 3ExamplePlace setup and analysis in their proper places
- 4TipDistinguish two missing-name problems
- 5ChallengeRecover after restarting R
- 6ExplanationRecognize the tidyverse collection
- 7ExampleResolve a same-name function
- 8Key InsightA table preview is not the full table
- 9ExamplePass a vector into its summary
- 10ExamplePass the summary into another call
- 11ChallengeCheck what the pipeline depends on
- 12RecapCheck availability, identity, and order
5Make a small analysis rerunnable
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive an analysis a lasting home
- 2ExplanationCreate the script before the session grows
- 3ExampleArrange creation before use
- 4TipLet comments explain decisions
- 5ChallengeExpose a hidden old object
- 6ExplanationOpen a project to establish the starting folder
- 7ExampleLocate one input inside the project
- 8Key InsightMove the project without changing its internal paths
- 9TipPreserve the original input
- 10ChallengeDiagnose a moved-project failure
- 11ExplanationMake names and spaces informative
- 12ExampleGive each pipeline stage a line
- 13ChallengeChoose the tool for the job
- 14ChallengeCheck the finished project
- 15RecapRun the saved record from the beginning
6Investigate a failed calculation
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn a surprise into a small question
- 2ExplanationFind the setting in the help page
- 3ExampleUse the documented default to explain NA
- 4ChallengeChoose a guide for the question
- 5ExplanationRead words instead of color
- 6ExampleInspect the first surprising result
- 7TipSearch for a generalizable error
- 8ExplanationCreate the same input for someone else
- 9ChallengeMake the example self-contained
- 10ChallengeCombine documentation with a diagnosis
- 11RecapShare a runnable question
R and RStudio practice questions
Set 1: First commands and everyday checks10 Practice Questions
Question 1 of 10
+ at the start of a new console input line after you typed sqrt(81. What is R waiting for?Show answerHide answer
+ is the continuation prompt: sqrt(81 has no closing parenthesis. Typing ) completes the call, while Esc cancels it. This prompt is different from an addition operator inside an expression, so entering another calculation does not finish the missing parenthesis.Question 2 of 10
3 + 4 * 2^2?Show answerHide answer
Question 3 of 10
mass_kg <- 6, then total_kg <- mass_kg * 4, then mass_kg <- 8. What does total_kg hold now?Show answerHide answer
total_kg still holds 24, the value calculated when mass_kg was 6. Assigning 8 to the input changes that object only. The value 32 would appear after rerunning the line that calculates total_kg; R objects do not keep live spreadsheet-style links to earlier inputs.Question 4 of 10
round(8.63) return with its default arguments?Show answerHide answer
digits is 0, so round(8.63) returns the nearest whole number, 9. Returning 8.6 would require digits = 1. Omitting an optional argument accepts its default; it does not infer a number of decimal places from the input.Question 5 of 10
typeof(12) return in R?Show answerHide answer
L suffix is stored as a double, even when its value is whole. typeof(12) therefore returns "double". The integer type would be created by 12L; the mathematical appearance of the printed number does not decide its R storage type.Question 6 of 10
c(FALSE, 4L, 2.5)?Show answerHide answer
FALSE converts to 0. The vector therefore contains 0, 4, and 2.5 as doubles. Converting everything to integer would lose the decimal part, but automatic combination follows the logical-to-integer-to-double-to-character order instead.Question 7 of 10
What does this code return?
x <- c(6, 11, 16, 21)
y <- x + c(1, 3)
y[y > 10 & y < 20]
Show answerHide answer
y equal to 7, 14, 17, 24. The two comparisons keep only values above 10 and below 20, so the result is 14 and 17. The result 11 and 16 applies the condition to the original x, overlooking the earlier addition.Question 8 of 10
Show answerHide answer
library(readr) attaches the installed package to the new session, making its exported functions available by name. Reinstalling readr only downloads it into a package library and does not attach it. The installation remains on disk after a restart, but the session attachment must be recreated.Question 9 of 10
data/visits.csv. What relative path points to that file?Show answerHide answer
"data/visits.csv" starts at the current project folder, enters its data subfolder, and names the file. A leading slash would instead start an absolute path from the filesystem root. Repeating a project-folder name would look for another nested folder that the scenario does not describe.Question 10 of 10
as.numeric(c("14", "unknown", "18")) returns a vector and the warning NAs introduced by coercion. What should you inspect next?Show answerHide answer
"unknown" could not become a number and was replaced by NA. Inspect that original value and decide how it should be handled. Suppressing or overlooking the warning would leave a new missing value in the result even though R completed the conversion call.Set 2: Use values, arguments, and saved code10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What does the final line return?
x <- c(5, 10, 15, 20)
y <- x
y[2] <- 30
y[y %in% x]
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
rep(c("dry", "wet"), each = 2) create?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
round(6,4) return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
answer <- round(mean(c(3, NA, 10)), 1)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
readings |> mean() |> round(2)?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
flow in the console. After restarting with workspace restoration off, sourcing fails at mean(flow). What change makes the script self-contained?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
avg<-mean(depth_cm,na.rm=TRUE) be spaced in tidyverse style?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What does the final line print?
length_m <- 7
width_m <- 3
area_m2 <- length_m * width_m
length_m <- 9
width_m <- 4
area_m2 <- length_m * width_m
width_m <- 5
area_m2
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
dplyr::near(0.2 + 0.4, 0.6) do?Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace results and repair a workflow10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Ctrl+L clears the RStudio console, what happens to an object you had already created?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
sample_count <- 18, then Sample_count <- 22. What happens when you print sample_count?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What does the final line return?
raw <- c("4", "missing", "9", "13")
z <- as.numeric(raw)
mean(z[z > 5], na.rm = TRUE)
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What does the final line return?
x <- c(8, 14, 20, 26)
y <- x[-c(1, 3)]
y <- y + c(1, 2, 3, 4)
y[y > 20]
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
A fresh session runs the code below. Both packages are installed. What makes the final selection reliably use dplyr?
library(dplyr)
library(MASS)
select(mtcars, mpg)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
"data/levels.csv". The file still exists inside the project. What should they do first?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Combine calculations, types, and session state10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
What value does this pipeline return?
values <- c(2.6, 3.6, NA, 8.6)
values |>
mean(na.rm = TRUE) |>
round()
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
-3^2 + 2 * 8 %% 3?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
seq(by = 4, from = 2, to = 14)?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What does the final line return?
a <- c(2, 5, 8)
b <- a + c(10, 20)
b[b >= 15]
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
as.numeric(c("11.5", "none", "8")) creates a new NA. Why can immediately adding na.rm = TRUE to a later mean hide a problem?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
x <- c(9, 18, 27), what does x[c(0, 2, 4)] return?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
data/raw.csv. Where should a corrected, derived table be written to preserve a rerunnable analysis?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
vals <- c("5", "9"), line 2 is avg <- mean(vals), and line 3 is round(avg). A warning occurs and the final result is NA. What repair addresses the earliest cause?Show answerHide answer
Save this lesson to see this answer.
Set 5: Apply the workflow in unfamiliar cases10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
round(4.5) == 4 & (17 %% 5 == 2)?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What does result hold after this code?
input <- 4
scaled <- input * 3
result <- scaled + 2
input <- 6
scaled <- input * 3
result
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What value is stored in answer?
x <- c(4, 9, NA, 12)
avg <- mean(x, na.rm = TRUE)
round(avg, 1)
answer <- round(avg * 3, 1)
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
readings?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What is the final value?
x <- c(3, 8, 13, 18, 23, 25)
y <- x[-c(2, 5)]
y <- y + c(2, 4)
mean(y[y >= 15])
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
round(mean_depth, 1) before mean_depth <- mean(c(2, 5, 9)). The next day it works after an unrelated console session created mean_depth <- 7. What change fixes both runs?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
What revision preserves the calculation and follows the usual multiline pipe style?
measures |> mean() |> round(1)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
read_csv() cannot be found. The readr package is installed. What setup is missing from the example?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absolute path
"/Users/lee/study/data.csv" works where that exact folder exists, regardless of getwd().Argument
round(7.326, digits = 2), the digits argument requests rounding to two decimal places.Arithmetic operator
* for multiplication or %% for a remainder.17 %% 6, the remainder operator returns 5 after two whole groups of 6 have been removed.Assignment
total <- count * 3 stores the current product; changing count later does not recalculate it.Atomic vector
c(4.2, 6.8, 9.1) holds three numeric measurements in their original observation order.C
Case sensitivity
Height and height refer to different objects.flow but asks for Flow, causing an object-name error in an empty session.Character type
"7"."7" needs numeric conversion before you can add 2 to its numeric value.Cheatsheet
Code style
Coercion
"pending" to a numeric vector with c() makes the combined atomic vector character data.Comment
# outside a string; R ignores it through the end of that line.# Exclude the test run explains a decision whose reason is not evident from the filter.Comparison operator
TRUE for 4 >= 4.depth_cm > 10 marks each depth above 10 cm with TRUE and each other known depth with FALSE.Console
length(readings) without adding the temporary check to your script.Continuation prompt
+ that R shows when it needs more input to finish the current command.CRAN
install.packages("readr") normally retrieves the package and required dependencies from CRAN.D
Debugging
Default argument
round(7.8) uses the default digits = 0, so R rounds the value to a whole number.Double type
L even when they look whole.7 and 7.5 are doubles, so a printed whole value does not guarantee integer storage.E
Environment
mean_depth was created before the next step.Error
Explicit conversion
as.numeric() or as.character().as.numeric() to the strings "2.4" and "5.6" before calculating their mean.F
Floating-point precision
Formatter
Function
sqrt(36) supplies 36 to a function and returns 6, which can be saved in an object.H
Help page
?median and inspect Usage to find the setting controlling missing-value removal.Help search
??"standard deviation" searches topics, helping you discover a function to investigate.I
Index
readings[c(1, 4)] selects the first and fourth values in the observation vector.Inf
Inf is R’s representation of infinity, which can occur in arithmetic such as dividing a positive finite number by zero.1 / 0 returns Inf, inspect the denominator before using that result in another calculation.Integer type
7L or the numbers generated by 1:5.typeof(7L) with typeof(7) to see integer storage beside double storage.L
Linter
List
list(12, "cm", TRUE) keeps a measurement, its text unit, and a logical flag together.Logical indexing
TRUE by a logical vector, often produced by a comparison.depths[depths > 15] keeps the known depths above the 15 cm threshold.Logical proportion
mean(scores >= 70) gives the proportion of scores meeting 70.Logical type
c(4, 9) > 6 produces the logical vector FALSE TRUE for the two positions.M
Masking
select() reach the MASS function instead of dplyr’s.Membership test
%in%.site %in% c("north", "east") to mark records whose site name belongs to either group.Message
Meta-package
N
NA
NA is R’s marker for a missing value, keeping a position in a vector even though the observation is unknown.c(8, NA, 12), the middle position is missing; is.na() identifies it without guessing its value.na.rm
na.rm argument controls whether many summary functions remove missing values before performing their calculation.mean(c(3, NA, 9), na.rm = TRUE) calculates from the two known observations and returns 6.Namespace
package::function() selects an exported definition without attachment.dplyr::near identifies the intended comparison function without attaching dplyr’s other names.NaN
NaN means “not a number” and represents an undefined numeric result, such as the result of dividing zero by zero.0 / 0 returns NaN, signaling an undefined calculation instead of an ordinary number.Native pipe
|> sends the result of its left-hand expression to the first argument of the call on its right.x |> mean() |> round(1) finds one mean before rounding that result to one decimal place.Nested call
round(sqrt(11), 1), R takes the square root before rounding that result to one decimal place.O
Object
mass_kg <- 52 creates an object whose name records the measurement’s unit.Operator precedence
4 + 3 * 2, multiplication comes first, so R returns 10 instead of adding 4 and 3 first.P
Package
Package attachment
library(readr) lets a later call use read_csv() without prefixing the package name.Package library
R
R
sqrt(49) in a console, and R carries out the calculation and returns the result 7.Recycling
c(3, 6, 9, 12) + c(1, 2), the shorter input repeats as 1, 2, 1, 2 before addition.Relative path
"figures/depth.png" stays useful after a project move if its internal layout is preserved.Reproducible example
RStudio
RStudio project
.Rproj file; opening it sets that folder as the working directory.S
Script
.R, arranged in the order the commands should run.Section comment
# Calculate summaries ---- creates an outline entry above the summary calculations.snake_case
mean_height_cm combines a summary, a measured quantity, and a unit without spaces.Sourcing
Summary function
sum(c(3, 5, 7)) reduces three observations to one total, while sqrt() acts on each.T
Tibble
Tidyverse
Truncation
as.integer() uses it when converting a non-whole numeric value.Type check
typeof() or true/false tests such as is.numeric().U
Usage section
median(x, na.rm = FALSE, ...) explains why missing inputs are retained unless requested otherwise.V
Vectorization
temps_c + 273.15 converts all stored Celsius temperatures to kelvin at once.Vignette
W
Warning
Working directory
getwd() reports the project root, "data/input.csv" names a file inside its data subfolder.Workspace
.RData and later restore, potentially hiding missing script steps.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.