R and RStudio Basics

Start analyzing data in R with no programming experience. Learn how R and RStudio work together, use R as a calculator, create objects and call functions, and work with vectors and their data types. Install and load packages, including the tidyverse, and chain steps with the pipe. Keep your work in scripts and RStudio projects with relative file paths, write code in a clear and consistent style, and find answers with help pages, error messages and reproducible examples.

BeginnerLesson 1 of 7 in Data Analysis with R Course

What you will learn

  1. 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 around
      Install 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 values
      Calculate with R's arithmetic operators and math functions, predict the order of operations, and compare values to get TRUE or FALSE.
  2. 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 objects
      Assign 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 arguments
      Call functions with arguments by position and by name, use default values, nest calls, and keep the results you need.
  3. 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 types
      Create vectors with c(), sequences and repetition, and tell logical, integer, double and character values apart.
    • Predict and control type conversion
      Predict how R coerces mixed values, convert types on purpose, and catch the warnings that signal failed conversions.
    • Calculate with vectors and select elements
      Apply vectorized arithmetic and summary functions, predict recycling, and pick elements by position or by condition.
  4. 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 packages
      Tell installing from loading, call package functions with ::, and fix the errors that come from missing or unloaded packages.
    • Use the tidyverse and resolve conflicts
      Load the core tidyverse packages, read the startup message, choose between functions with the same name, and chain steps with the pipe.
  5. 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 scripts
      Write 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 paths
      Keep 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 style
      Name objects, space code, break lines and comment consistently, following the tidyverse style guide, and let tools tidy code for you.
  6. 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 documentation
      Open 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 well
      Tell errors, warnings and messages apart, recognize common errors and their fixes, search for solutions, and share a minimal reproducible example.

R and RStudio study guide

6 chapters

1

Get 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^2 differs 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, and Inf.
2

Create 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 nameInvalid nameReason for rejection
temp_ctemp cContains a space
temp22tempStarts with a digit
mean_height_heightStarts 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 <- value creates 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, and rm() 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 = TRUE calculates 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.
3

Work 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
TypeExampleMeaning
LogicalTRUEA true/false value
Integer5LA whole number stored as an integer
Double5 or 2.5A 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(), and rep() for regular sequences and repetition.
  • Logical, integer, double, and character are the main atomic types; integer and double are numeric.
  • typeof(5) is "double", while typeof(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; use round() 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] returns NA, and x[0] returns numeric(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.
4

Extend 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
PackageMain job
ggplot2Graphs
dplyrData transformation
tidyrData tidying
readrReading rectangular files
tibbleModern data frames
stringrWorking with text
forcatsWorking with factors
lubridateDates and times
purrrApplying 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.
5

Organize 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 .Rproj file 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_case names 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.
6

Find 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 problemFirst 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

6 Walkthroughs

1

Run and understand your first commands

12 steps
Move from an RStudio console prompt to calculations and logical checks you can interpret.
  1. 1
    IntroductionStart 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.

  2. 2
    ExplanationFind 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.

  3. 3
    ExampleRead a result without its position label

    At the > prompt, type 2 + 6 and press Enter. R displays:

    [1] 8
    

    The 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.

  4. 4
    TipRecover from an unfinished command

    Type sqrt(36 without 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.

  5. 5
    ChallengeExplain 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.

  6. 6
    ExplanationLet the operators determine the order

    R uses * for multiplication and ^ for powers. In 2 + 3 * 4, it multiplies first, giving 14. Parentheses change the grouping: (2 + 3) * 4 gives 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.

  7. 7
    ExampleCalculate with a measurement

    A walker travels 9 km in 2 hours. Enter:

    9 / 2
    

    R 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.

  8. 8
    Key InsightKeep a negative base inside parentheses

    A power binds more tightly than a leading minus. -3^2 means the negative of 3^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^2 means 2^(3^2). Multiplication and division instead group from the left, so 24 / 3 / 2 is 4.

  9. 9
    ExampleUse 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 and round(5.5) gives 6.

  10. 10
    ConnectionTurn a result into a test

    Comparisons produce logical values. 4.5 > 4 is TRUE, while 4.5 == 4 is FALSE. 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.

  11. 11
    ChallengeTrace a complete condition

    What logical result does (3 + 5) / 2 >= 4 & 13 %% 4 == 1 return?

    ---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 is TRUE. At the console, a new > prompt means R is ready for the next command.

  12. 12
    RecapKeep 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.

2

Build a calculation with named inputs

13 steps
Create objects, call functions, and see why saved results must be recalculated after changes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild a short chain of results
  2. 2
    ExplanationStore the starting values
  3. 3
    ExampleCreate the first dependent value
  4. 4
    ExampleChange one input
  5. 5
    ChallengeFind the value that stayed behind
  6. 6
    ExplanationIdentify an argument and a default
  7. 7
    ExampleName inputs to remove positional doubt
  8. 8
    ExampleHandle a missing observation
  9. 9
    ChallengeKeep the setting in the right call
  10. 10
    Key InsightDisplaying is different from replacing
  11. 11
    TipDistinguish text from a name
  12. 12
    ChallengeFollow creation, calculation, and storage
  13. 13
    RecapInspect the chain in running order
3

Build, convert, and select observations

17 steps
Follow one vector through type checks, conversions, arithmetic, and logical selection.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionWatch values and their structure
  2. 2
    ExplanationBuild a vector in observation order
  3. 3
    ExampleInspect what a number is made of
  4. 4
    TipChoose a sequence or repetition pattern
  5. 5
    ChallengeChoose the missing-value test
  6. 6
    ExplanationPredict a shared type
  7. 7
    ExampleLocate a failed conversion
  8. 8
    Key InsightA logical mean is a proportion
  9. 9
    ChallengeConvert before choosing a comparison
  10. 10
    ExplanationMatch observations by position
  11. 11
    ExampleRepeat one value or a short pattern
  12. 12
    TipTreat a length warning as a pairing check
  13. 13
    ExampleKeep or omit positions
  14. 14
    ExampleUse a condition as the index
  15. 15
    ConnectionTest membership and change a copy
  16. 16
    ChallengeTrace a changed vector into a summary
  17. 17
    RecapInspect before you summarize
4

Use a package and follow a pipeline

12 steps
Separate package setup from session use, then resolve names and chain calls.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow a tool from disk into a calculation
  2. 2
    AnalogyPut a book on the shelf
  3. 3
    ExamplePlace setup and analysis in their proper places
  4. 4
    TipDistinguish two missing-name problems
  5. 5
    ChallengeRecover after restarting R
  6. 6
    ExplanationRecognize the tidyverse collection
  7. 7
    ExampleResolve a same-name function
  8. 8
    Key InsightA table preview is not the full table
  9. 9
    ExamplePass a vector into its summary
  10. 10
    ExamplePass the summary into another call
  11. 11
    ChallengeCheck what the pipeline depends on
  12. 12
    RecapCheck availability, identity, and order
5

Make a small analysis rerunnable

15 steps
Save ordered code, establish a project root, and check the work from a fresh session.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive an analysis a lasting home
  2. 2
    ExplanationCreate the script before the session grows
  3. 3
    ExampleArrange creation before use
  4. 4
    TipLet comments explain decisions
  5. 5
    ChallengeExpose a hidden old object
  6. 6
    ExplanationOpen a project to establish the starting folder
  7. 7
    ExampleLocate one input inside the project
  8. 8
    Key InsightMove the project without changing its internal paths
  9. 9
    TipPreserve the original input
  10. 10
    ChallengeDiagnose a moved-project failure
  11. 11
    ExplanationMake names and spaces informative
  12. 12
    ExampleGive each pipeline stage a line
  13. 13
    ChallengeChoose the tool for the job
  14. 14
    ChallengeCheck the finished project
  15. 15
    RecapRun the saved record from the beginning
6

Investigate a failed calculation

11 steps
Use documentation and a small reproducible example to find the first cause of a problem.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn a surprise into a small question
  2. 2
    ExplanationFind the setting in the help page
  3. 3
    ExampleUse the documented default to explain NA
  4. 4
    ChallengeChoose a guide for the question
  5. 5
    ExplanationRead words instead of color
  6. 6
    ExampleInspect the first surprising result
  7. 7
    TipSearch for a generalizable error
  8. 8
    ExplanationCreate the same input for someone else
  9. 9
    ChallengeMake the example self-contained
  10. 10
    ChallengeCombine documentation with a diagnosis
  11. 11
    RecapShare a runnable question

R and RStudio practice questions

50 Practice Questions in 5 sets

Set 1: First commands and everyday checks10 Practice Questions

Question 1 of 10

RStudio shows a + at the start of a new console input line after you typed sqrt(81. What is R waiting for?
  1. An instruction to install sqrt()
  2. A command to clear the console
  3. The rest of the unfinished call
  4. Permission to print a result
Show answerHide answer
Answer: C
The leading + 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

What value does R return for 3 + 4 * 2^2?
  1. 28
  2. 19
  3. 35
  4. 64
Show answerHide answer
Answer: B
R evaluates the power first, giving 4, and then multiplies 4 by 4 before adding 3. The result is 19. The value 28 comes from adding 3 and 4 first, but there are no parentheses that would give addition priority over multiplication.

Question 3 of 10

You run mass_kg <- 6, then total_kg <- mass_kg * 4, then mass_kg <- 8. What does total_kg hold now?
  1. 32
  2. 8
  3. 6
  4. 24
Show answerHide answer
Answer: D
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

What does round(8.63) return with its default arguments?
  1. 8
  2. 9
  3. 8.6
  4. 8.63
Show answerHide answer
Answer: B
The default for 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

What does typeof(12) return in R?
  1. "integer"
  2. "character"
  3. "double"
  4. "logical"
Show answerHide answer
Answer: C
A number typed without an 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

What are the values and type of c(FALSE, 4L, 2.5)?
  1. 0, 4, 2.5; double
  2. FALSE, TRUE, TRUE; logical
  3. 0, 4, 2; integer
  4. "FALSE", "4", "2.5"; character
Show answerHide answer
Answer: A
The double value 2.5 makes the common type double, and 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]
  1. 11, 16
  2. 14, 19
  3. 7, 14
  4. 14, 17
Show answerHide answer
Answer: D
The shorter vector recycles as 1, 3, 1, 3, making 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

You installed readr yesterday and have just started a new R session. What makes its exported functions available by their bare names?
  1. library(readr)
  2. install.packages("readr")
  3. packageVersion("readr")
  4. help("readr")
Show answerHide answer
Answer: A
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

The working directory is a project folder containing data/visits.csv. What relative path points to that file?
  1. "visits.csv/data"
  2. "project/data/visits.csv"
  3. "data/visits.csv"
  4. "/data/visits.csv"
Show answerHide answer
Answer: C
"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?
  1. The original value that became NA
  2. The color of the console output
  3. The default number of printed digits
  4. The list of previously run commands
Show answerHide answer
Answer: A
The warning reports a conversion failure: "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]
  1. 5, 10, 15, 20
  2. 5, 30, 15, 20
  3. 5, 15, 20
  4. 5, 20
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What vector does rep(c("dry", "wet"), each = 2) create?
  1. "dry", "dry", "wet", "wet"
  2. "dry", "wet", "dry", "wet"
  3. "dry", "dry", "dry", "dry"
  4. "wet", "wet", "dry", "dry"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does round(6,4) return?
  1. 6.4
  2. 6
  3. 10
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What result is stored by answer <- round(mean(c(3, NA, 10)), 1)?
  1. 6.5
  2. 6
  3. 13
  4. NA
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What nested call is equivalent to readings |> mean() |> round(2)?
  1. mean(round(readings), 2)
  2. round(mean(readings), 2)
  3. round(readings, mean(2))
  4. mean(round(readings, 2))
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A script works only after you create flow in the console. After restarting with workspace restoration off, sourcing fails at mean(flow). What change makes the script self-contained?
  1. Save the console display beside the script
  2. Clear the console before sourcing the script
  3. Move mean(flow) to the top of the script
  4. Add the creation of flow before its use
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

How should avg<-mean(depth_cm,na.rm=TRUE) be spaced in tidyverse style?
  1. avg <- mean(depth_cm, na.rm = TRUE)
  2. avg <- mean (depth_cm, na.rm=TRUE)
  3. avg<-mean(depth_cm , na.rm = TRUE)
  4. avg <- mean( depth_cm,na.rm=TRUE )
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Which part of a function help page shows the call signature and its argument defaults?
  1. Value
  2. Examples
  3. Usage
  4. See Also
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
  1. 21
  2. 45
  3. 35
  4. 36
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

dplyr is installed but not attached. What does calling dplyr::near(0.2 + 0.4, 0.6) do?
  1. Attaches every exported dplyr function
  2. Calls near() without attaching dplyr
  3. Installs dplyr before calling near()
  4. Requires library(dplyr) to run first
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

After Ctrl+L clears the RStudio console, what happens to an object you had already created?
  1. It becomes a missing value
  2. It is removed from memory
  3. It stays in the R session
  4. It is saved into a script
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

You created sample_count <- 18, then Sample_count <- 22. What happens when you print sample_count?
  1. It returns 18
  2. It returns 22
  3. It returns 40
  4. It reports no object
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)
  1. 6.5
  2. NA
  3. 13
  4. 11
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]
  1. 14, 26
  2. 28, 30
  3. 15, 28
  4. 22, 29
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)
  1. Rename mtcars before the call
  2. Reinstall dplyr before the call
  3. Call dplyr::select(mtcars, mpg)
  4. Call MASS::select(mtcars, mpg)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

R reports an object is missing on line 6 of a script, and lines 7–9 then fail too. What should you investigate first?
  1. The syntax of every later line
  2. The number of saved script files
  3. The formatting of the console
  4. The failed dependency on line 6
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A colleague moves an intact project folder, opens only its script, and gets a missing-file error for "data/levels.csv". The file still exists inside the project. What should they do first?
  1. Inspect getwd() and open the project
  2. Replace every path with your home path
  3. Move the data outside the project
  4. Install the package used for the file
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What does a code formatter such as Air primarily change?
  1. The observations in a vector
  2. The formatting of the code
  3. The intended analysis question
  4. The computed numeric precision
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

You do not know the function name for standard deviation. What built-in search looks through installed help topics for that phrase?
  1. args("standard deviation")
  2. example("standard deviation")
  3. ??"standard deviation"
  4. typeof("standard deviation")
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A forum helper cannot rerun a screenshot of your error. What information would make the problem reproducible?
  1. All screenshots from the same session
  2. Only the final value you expected
  3. Only the installed R version string
  4. Small runnable code with data and output
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()
  1. 6
  2. 5
  3. 4
  4. NA
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What value does R return for -3^2 + 2 * 8 %% 3?
  1. 13
  2. -8
  3. 10
  4. -5
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What is the result of seq(by = 4, from = 2, to = 14)?
  1. 2, 6, 10, 14
  2. 4, 6, 8, 10, 12, 14
  3. 2, 4, 6, 8, 10, 12, 14
  4. 4, 8, 12
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]
  1. 25, 28, with no warning
  2. 25, 18, after a warning
  3. 12, 25, 18, after a warning
  4. 12, 18, with no warning
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?
  1. It converts the numeric results back to text
  2. It rounds all remaining values to integers
  3. It omits evidence of a failed conversion
  4. It restores the original unconverted string
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For x <- c(9, 18, 27), what does x[c(0, 2, 4)] return?
  1. NA, 18, NA
  2. 9, 18, 27
  3. 18, NA
  4. 18, 27
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What command reports the installed version of readr?
  1. packageVersion("readr")
  2. library(readr)
  3. install.packages("readr")
  4. getwd()
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A script reads raw measurements from data/raw.csv. Where should a corrected, derived table be written to preserve a rerunnable analysis?
  1. Over the original data/raw.csv file
  2. Into the restored workspace only
  3. Over the project configuration file
  4. To a separate file in output/
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An AI suggests a function call you have never used. How can you check that it performs the calculation you need?
  1. Accept it if the explanation is detailed
  2. Check only whether its name sounds right
  3. Read its help and test a known-answer input
  4. Run it once on the full data and save it
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

In an empty session, line 1 is 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?
  1. Convert and inspect vals before the mean
  2. Round each quoted value before the mean
  3. Add na.rm = TRUE to the current mean
  4. Restart and run only the rounding line
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

A colleague has installed R but cannot find RStudio’s source editor or Files pane in a plain R terminal. What explains this?
  1. The panes require attaching the tidyverse first
  2. RStudio adds those panes around the R engine
  3. Opening a project in plain R creates those panes
  4. Updating R adds the editor and Files pane
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What are the rounded value and the final logical result in round(4.5) == 4 & (17 %% 5 == 2)?
  1. 5 and FALSE
  2. 4 and FALSE
  3. 5 and TRUE
  4. 4 and TRUE
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
  1. 14
  2. 20
  3. 18
  4. 12
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)
  1. 24.9
  2. 8.3
  3. 25
  4. NA
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What test returns a logical vector identifying the missing elements of readings?
  1. readings == NA
  2. is.na(readings)
  3. typeof(readings)
  4. length(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])
  1. 20
  2. 21.5
  3. 22
  4. 23
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A tibble preview shows only 10 rows of an object described as having 320 rows. What does that mean?
  1. The stored table has only 10 rows
  2. The other 310 rows failed to load
  3. The table lost rows during printing
  4. The display is a preview of 320 rows
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

In an empty session with restoration disabled, a script runs 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?
  1. Move the mean assignment before its first use
  2. Restore the old mean from the saved workspace
  3. Assign the rounded result back to mean_depth
  4. Round the input vector instead of its mean
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)
  1. measures
      |> mean()
      |> round(1)
    
  2. measures |>
      round(1) |>
      mean()
    
  3. measures |>
      mean() |>
      round(1)
    
  4. measures |>
    mean |>
    round(1)
    
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A reprex works in your current console but fails in its fresh session because read_csv() cannot be found. The readr package is installed. What setup is missing from the example?
  1. An install.packages("readr") call
  2. A library(tidyr) call
  3. A library(tibble) call
  4. A library(readr) call
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

70 Key Terms, each with its definition

A

Absolute path
An absolute path specifies a complete file location from a drive or filesystem root and does not depend on the working directory.
The path "/Users/lee/study/data.csv" works where that exact folder exists, regardless of getwd().
Argument
An argument is an input or setting supplied inside a function call, matched by its name or by its position in the call.
In round(7.326, digits = 2), the digits argument requests rounding to two decimal places.
Arithmetic operator
An arithmetic operator is a symbol that performs a numeric operation, such as * for multiplication or %% for a remainder.
In 17 %% 6, the remainder operator returns 5 after two whole groups of 6 have been removed.
Assignment
Assignment stores the result of an expression under an object name, creating that name or replacing its previous value.
The line total <- count * 3 stores the current product; changing count later does not recalculate it.
Atomic vector
An atomic vector is an ordered collection whose elements share one storage type, such as double or character.
The vector c(4.2, 6.8, 9.1) holds three numeric measurements in their original observation order.

C

Case sensitivity
Case sensitivity means uppercase and lowercase letters distinguish names, so Height and height refer to different objects.
A script creates flow but asks for Flow, causing an object-name error in an empty session.
Character type
The character type stores text strings, including numeric-looking values enclosed in quotes, such as "7".
The character value "7" needs numeric conversion before you can add 2 to its numeric value.
Cheatsheet
A cheatsheet is a compact reference that groups useful commands or distinctions for quick lookup during work or review.
You consult a Posit cheatsheet to recall a command, then open its full documentation for the details.
Code style
Code style is a consistent set of conventions for names, spaces, comments, and line breaks that makes code easier to read.
You apply the tidyverse style throughout a shared analysis so the layout stays predictable for readers.
Coercion
Coercion is automatic conversion to a common type when an operation combines values whose original types differ.
Adding "pending" to a numeric vector with c() makes the combined atomic vector character data.
Comment
A comment is explanatory text beginning with # outside a string; R ignores it through the end of that line.
The comment # Exclude the test run explains a decision whose reason is not evident from the filter.
Comparison operator
A comparison operator tests a relationship between values and returns logical results, such as TRUE for 4 >= 4.
The test depth_cm > 10 marks each depth above 10 cm with TRUE and each other known depth with FALSE.
Console
A console is an interactive place to enter R commands and read their output, prompts, errors, warnings, and messages.
You use the console to check length(readings) without adding the temporary check to your script.
Continuation prompt
A continuation prompt is the leading + that R shows when it needs more input to finish the current command.
After an unclosed function call, you type the final parenthesis at the continuation prompt.
CRAN
CRAN, the Comprehensive R Archive Network, distributes R itself and hosts a large collection of contributed R packages.
The call install.packages("readr") normally retrieves the package and required dependencies from CRAN.

D

Debugging
Debugging is the process of locating and correcting the cause of unwanted code behavior by inspecting steps and inputs.
You debug from the first failure, printing intermediate objects before considering errors that follow it.
Default argument
A default argument is a predefined setting used when the caller leaves that optional argument out of a function call.
The call round(7.8) uses the default digits = 0, so R rounds the value to a whole number.
Double type
The double type stores floating-point numeric values, including numbers typed without L even when they look whole.
Both 7 and 7.5 are doubles, so a printed whole value does not guarantee integer storage.

E

Environment
An environment holds bindings between names and objects; RStudio’s Environment pane shows objects available in your workspace.
You inspect the Environment pane to check whether mean_depth was created before the next step.
Error
An error is a reported failure that stops the affected code, often naming the function and describing the problem.
An object-not-found error makes you check spelling, case, and whether the creation line actually ran.
Explicit conversion
Explicit conversion changes a value’s type through a requested call such as as.numeric() or as.character().
You apply as.numeric() to the strings "2.4" and "5.6" before calculating their mean.

F

Floating-point precision
Floating-point precision is the limited accuracy used to represent numbers in binary, which can introduce tiny decimal differences.
You use a tolerance when comparing calculated decimals that differ only through storage error.
Formatter
A formatter rewrites code layout, such as spaces, indentation, and line breaks, according to a chosen style.
Air or styler can reformat a call while you review separately whether it calculates the intended result.
Function
A function is callable code that performs an operation on supplied inputs and returns a result for further use.
The call sqrt(36) supplies 36 to a function and returns 6, which can be saved in an object.

H

Help page
A help page documents a function or topic, with sections describing usage, arguments, returned values, and runnable examples.
You open ?median and inspect Usage to find the setting controlling missing-value removal.
Help search
A help search looks for a word or phrase in installed documentation when the name of the needed function is unknown.
The query ??"standard deviation" searches topics, helping you discover a function to investigate.

I

Index
An index identifies positions or conditions used inside square brackets to select or replace elements of an object.
The index in 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.
When 1 / 0 returns Inf, inspect the denominator before using that result in another calculation.
Integer type
The integer type stores whole-number values, such as the literal 7L or the numbers generated by 1:5.
You compare typeof(7L) with typeof(7) to see integer storage beside double storage.

L

Linter
A linter checks code for style or other issues and reports them for review without rewriting the source file.
You use lintr to locate style problems, then decide which reported issues need changes in the script.
List
A list is a collection that can hold separate components with different types and lengths, unlike an atomic vector.
The list list(12, "cm", TRUE) keeps a measurement, its text unit, and a logical flag together.
Logical indexing
Logical indexing selects values at positions marked TRUE by a logical vector, often produced by a comparison.
The expression depths[depths > 15] keeps the known depths above the 15 cm threshold.
Logical proportion
A logical proportion is the mean of true/false values treated as 1 and 0, giving the fraction of known tests that are true.
With no missing values, mean(scores >= 70) gives the proportion of scores meeting 70.
Logical type
The logical type stores true, false, or missing values and commonly holds the results of tests and comparisons.
The expression c(4, 9) > 6 produces the logical vector FALSE TRUE for the two positions.

M

Masking
Masking occurs when a same-named object takes priority in name lookup, such as a function in a newly attached package.
Attaching MASS after dplyr can make a bare select() reach the MASS function instead of dplyr’s.
Membership test
A membership test checks whether each value occurs anywhere in a supplied set; R expresses this with %in%.
You use site %in% c("north", "east") to mark records whose site name belongs to either group.
Message
A message gives information during execution, such as a package startup report, without being an error or warning.
The tidyverse startup message identifies attached packages and conflicts after the load has succeeded.
Meta-package
A meta-package provides convenient installation of a related collection; tidyverse also attaches its core packages together.
The tidyverse meta-package saves you from installing and attaching each core package separately.

N

NA
NA is R’s marker for a missing value, keeping a position in a vector even though the observation is unknown.
In c(8, NA, 12), the middle position is missing; is.na() identifies it without guessing its value.
na.rm
The na.rm argument controls whether many summary functions remove missing values before performing their calculation.
Using mean(c(3, NA, 9), na.rm = TRUE) calculates from the two known observations and returns 6.
Namespace
A namespace keeps a package’s definitions together; package::function() selects an exported definition without attachment.
The name 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.
The expression 0 / 0 returns NaN, signaling an undefined calculation instead of an ordinary number.
Native pipe
The native pipe |> sends the result of its left-hand expression to the first argument of the call on its right.
The pipeline x |> mean() |> round(1) finds one mean before rounding that result to one decimal place.
Nested call
A nested call places one function call inside another, so the inner result becomes an input to the outer function.
In round(sqrt(11), 1), R takes the square root before rounding that result to one decimal place.

O

Object
An object is a value stored under a name in R’s memory so that code can inspect it or use it in later operations.
The assignment mass_kg <- 52 creates an object whose name records the measurement’s unit.
Operator precedence
Operator precedence is the order in which R applies different operations in an expression without extra parentheses.
In 4 + 3 * 2, multiplication comes first, so R returns 10 instead of adding 4 and 3 first.

P

Package
A package is a distributable bundle of R functions, data, and documentation that extends what an R installation can do.
You install readr to obtain its file-reading functions and the documentation explaining their arguments.
Package attachment
Package attachment makes an installed package’s exported names available to ordinary calls in the current R session.
Running library(readr) lets a later call use read_csv() without prefixing the package name.
Package library
A package library is a folder on disk containing installed packages, separate from the objects in a running R session.
Restarting R removes session attachments but leaves the packages in their library available to load.

R

R
R is a free, open-source programming language and computing environment used for statistics, data analysis, and graphics.
You enter sqrt(49) in a console, and R carries out the calculation and returns the result 7.
Recycling
Recycling repeats a shorter input to match a longer one; base R warns when the longer length is not a multiple of the shorter.
In c(3, 6, 9, 12) + c(1, 2), the shorter input repeats as 1, 2, 1, 2 before addition.
Relative path
A relative path locates a file from the working directory instead of specifying its complete location from the filesystem root.
The path "figures/depth.png" stays useful after a project move if its internal layout is preserved.
Reproducible example
A reproducible example is small, self-contained code and data that let someone else recreate the behavior you need help with.
You replace a private data file with a short vector and keep only the call that still produces the problem.
RStudio
RStudio is an integrated development environment from Posit that combines an R editor with tools for running and inspecting code.
You write an analysis in RStudio’s source editor and send expressions to its console to run them.
RStudio project
An RStudio project groups an analysis around a folder and .Rproj file; opening it sets that folder as the working directory.
Your colleague opens the project before running its scripts, establishing the same relative-path starting point.

S

Script
A script is a saved plain-text file of R code, usually ending in .R, arranged in the order the commands should run.
You reopen a script to rerun the calculations that created yesterday’s table from its input data.
Section comment
A section comment ends with at least four dashes and marks a navigable heading in RStudio’s script outline.
The line # Calculate summaries ---- creates an outline entry above the summary calculations.
snake_case
Snake_case is a naming convention that joins lowercase words with underscores, making multiword object names readable.
The name mean_height_cm combines a summary, a measured quantity, and a unit without spaces.
Sourcing
Sourcing runs the code in a script from beginning to end, so required data and objects must be available in order.
After restarting R, you source the analysis to check that its creation steps precede every use.
Summary function
A summary function combines multiple input values into a smaller result, commonly one number such as a sum or mean.
The call sum(c(3, 5, 7)) reduces three observations to one total, while sqrt() acts on each.

T

Tibble
A tibble is a modern data frame used in the tidyverse, with concise printing that displays dimensions and column types.
A tibble preview shows 10 rows of a larger table while retaining the unprinted rows in the object.
Tidyverse
The tidyverse is a collection of R packages for data science that share design conventions and compatible data structures.
You attach the core tidyverse to work with related tools for reading, transforming, and plotting data.
Truncation
Truncation removes the fractional part toward zero; as.integer() uses it when converting a non-whole numeric value.
The value -4.9 becomes -4 under integer conversion, showing why truncation differs from rounding.
Type check
A type check inspects how an object is stored, using tools such as typeof() or true/false tests such as is.numeric().
Before repairing a failed mean calculation, you check whether the input is numeric or text.

U

Usage section
The Usage section of an R help page shows the call signature, including argument names, their order, and defaults.
The signature median(x, na.rm = FALSE, ...) explains why missing inputs are retained unless requested otherwise.

V

Vectorization
Vectorization applies an operation to the elements of a vector in one call, often returning one result per position.
The expression temps_c + 273.15 converts all stored Celsius temperatures to kelvin at once.
Vignette
A vignette is a longer package guide that connects functions through explanations and examples of a complete task.
You browse dplyr’s vignettes when a single function reference does not show how the steps fit together.

W

Warning
A warning reports a possible problem while evaluation continues, so the resulting value needs inspection before use.
A conversion warning makes you examine which text values became missing instead of using the result uncritically.
Working directory
The working directory is the starting folder R uses when resolving a relative path to read or write a file.
When getwd() reports the project root, "data/input.csv" names a file inside its data subfolder.
Workspace
A workspace holds session objects that R can save in .RData and later restore, potentially hiding missing script steps.
Disabling workspace restoration makes a new session reveal objects created only in earlier console work.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started