Working in R and RStudio: Objects, Data Frames, Import Checks, and Reproducible Scripts
Two different things, and why the distinction matters
R is the language and the engine that evaluates your code.
RStudio is an integrated development environment that runs R for you and arranges four panes around it: a source editor for scripts, a console where expressions are evaluated, an environment pane listing the objects that currently exist, and a pane holding files, plots, packages and help.
The practical consequence is a rule worth adopting from the first session: preserve your work in a saved script or other executable document, not solely in the console.
A command typed directly into the console is evaluated once and is not automatically preserved as a reproducible record, and the objects it assigns remain only in the current session unless you explicitly save them.
Some console commands do leave persistent effects, write.csv(), saveRDS() and file.create() all write to disk, but those files alone do not preserve a reliable, readable sequence of commands that a colleague can rerun.
A saved script or other executable document preserves a readable sequence that a colleague can rerun; commands entered only in the console are not a reliable shared record. Use the console for exploring and the editor for anything you intend to keep.
Objects and assignment
Assignment uses the arrow operator, written as a less-than sign followed by a hyphen: heights <- c(12.4, 15.1, 9.8).
The equals sign also assigns in most contexts, but the arrow is conventional in R and reads unambiguously, because = is also used for naming function arguments.
Assigned objects appear in the environment pane, which is a useful check that a line did what you expected.
Atomic vectors have exactly one type
The fundamental R data structure is the atomic vector: an ordered collection in which every element has the same type.
When c() is given atomic values of different types, it does not error and it does not keep them separate. It coerces everything to the single most general type present, following the hierarchy logical → integer → double → complex → character.
The rule is stated for atomic inputs deliberately: if any argument is itself a list, c() returns a list rather than an atomic vector, so c(1, list("x")) is a two-element list holding a double and a character string rather than one coerced type.
So c(TRUE, 3L) gives the integers 1 and 3, c(3L, 2.5) gives doubles, and c(2.5, "kg") gives the character strings "2.5" and "kg".
The rule is convenient when you intend it and dangerous when you do not, because a single stray text value anywhere in a column silently converts the entire column to text.
The effect depends on the operation: mean() on a character column warns and returns no numeric mean, while arithmetic operators such as + error. Character comparisons and sorting may proceed lexically: as text, "10" sorts before "9".
Coercion also runs in the useful direction. Logical values become 1 and 0 in arithmetic, so when the comparison has no NA values, sum(x > 40) counts how many elements exceed 40, and mean(x > 40) gives the proportion that do.
For x <- c(41, NA), both expressions return NA by default; if missing values are possible, choose and state a rule such as na.rm = TRUE, which computes over the non-missing comparisons.
Operations are vectorised: heights * 10 multiplies every element. Compatible vectorised operations such as arithmetic recycle the shorter operand to match the longer one.
For two nonempty vectors of different lengths, R warns if the shorter length does not divide the longer length; if it divides evenly, recycling is silent.
This does not describe c(): c(c(1, 2), c(3, 4, 5)) concatenates five elements without recycling or a warning.
Subsetting, and subsetting as assignment
Square brackets extract by position, by negative position, by name, or by a logical vector:
scores <- c(58, 73, 41, 90, 66)
scores[2] # 73, the second element
scores[-1] # everything except the first
scores[scores > 65] # 73, 90 and 66Logical subsetting works because scores > 65 produces a logical vector of the same length, and the bracket keeps the positions marked TRUE.
The same expression on the left of an assignment replaces the selected positions in place: scores[scores < 50] <- 50 raises every value below 50 up to 50 and leaves the rest untouched.
This is the idiomatic way to recode or cap values, and it changes the object rather than returning a copy.
Data frames and the two-index contract
A data frame is a rectangular table with equal-length columns. Ordinary atomic columns, including the columns imported from the CSV examples here, each have one type; a data frame may also contain list columns, whose elements need not share a type.
Extract a column with df$column, and subset the table with the two-index form df[rows, columns].
The comma is part of the operator, not decoration. df[df$mass > 20, ] keeps the rows satisfying the condition and, because the column index is left blank, all columns. df[df$mass > 20] supplies only one index, and for a data frame a single index selects columns, exactly as it would for a list.
Leaving out the comma therefore selects columns rather than filtering rows. It raises an undefined-columns error if the logical index has a TRUE beyond the last available column; selecting only existing columns succeeds.
For example, for a two-column data frame, df[c(TRUE, FALSE)] returns a one-column data frame containing the first column.
One further subtlety: when the two-index form selects a single column, R simplifies the result to a bare vector by default. df[df$mass > 20, "mass"] returns a vector of the mass column's type (numeric if df$mass is numeric), while df[df$mass > 20, "mass", drop = FALSE] returns a one-column data frame.
Code that expects a data frame and receives a vector fails in confusing ways downstream.
A version-dependent detail worth knowing: from R 4.0.0 onward, read.csv() and data.frame() leave text columns as character by default. In earlier versions they were converted to factors unless stringsAsFactors = FALSE was given.
Scripts and tutorials written before that change behave differently under a modern R, which is a frequent source of confusion when reading older material.
Importing, then looking before you calculate
Read a delimited file with read.csv("data/plots.csv"). The path is interpreted relative to the current working directory, which getwd() reports.
The robust arrangement is to keep the data inside a project folder and open that folder as an RStudio project.
The project normally starts with its root as the working directory; relative paths resolve from that root only while the working directory remains there. For example, after setwd("data"), read.csv("data/plots.csv") would look inside a second data subfolder.
Check getwd() when a path fails. The same project-relative paths can work on another machine when the folder structure is preserved and the working directory is the project root.
Immediately after importing, inspect rather than calculate. str() is the single most useful diagnostic: it reports the number of observations, the number of variables, and the type of every column with a few example values. head(), nrow(), summary() and class() fill in the rest.
The reason to run str() first is that a printed table looks identical whether a column is numeric or text, and the difference only announces itself later, as a failed calculation or a lexical sort.
Worked example of the commonest import defect. Suppose a file records masses as "4.6 g" rather than 4.6. Because every value carries the suffix, no value parses as a number and the whole column arrives as character. Strip the suffix and convert:
samples <- read.csv("data/samples.csv")
str(samples)
samples$mass <- as.numeric(gsub(" g", "", samples$mass_text))
sum(is.finite(samples$mass)) # should equal nrow(samples)That last line is a finiteness check: it tests whether every converted value is finite. Failed parsing often produces NA, and missing inputs can remain missing; successfully parsed Inf, -Inf and NaN are non-finite too.
If the count is below nrow(), inspect each flagged original text value beside its converted result before deciding whether a unit variant, separator or other format caused a parse failure. The finite count establishes finiteness, not the cause.
Summaries and simple plots
Basic summaries are mean(), median(), sd(), range(), length() and table(). Group-wise summaries use the formula interface, as in aggregate(mass ~ treatment, data = samples, FUN = mean).
The same formula notation drives base graphics: plot(mass ~ height, data = samples) for a scatterplot, hist(samples$mass) for a distribution, and boxplot(mass ~ treatment, data = samples) for a group comparison.
Reading a formula as “response on the left, explanatory variable on the right” makes the pattern consistent across summaries, plots and models.
What makes a script reproducible
A reproducible script produces the same result when run from top to bottom in a fresh R session by somebody else on a different machine. Three habits cover most of it.
- Never hard-code an absolute path. A line pointing at one user's desktop fails wherever that absolute directory is absent and makes the script depend on a machine-specific directory layout. Use a project and relative paths instead of setwd().
- Declare dependencies in the script. Every library() call belongs at the top. A script that calls a function from a package attached only interactively can run in that session but fail in a fresh session without the package attached.
- Seed anything random. Without a fixed seed, repeated calls such as sample() may give different output, although a sample can repeat by chance.
The test is mechanical rather than a matter of judgement: restart R without restoring the saved workspace, open the project fresh, and run the whole script.
A fresh-session run checks for hidden workspace dependencies: if it fails, the failure point names the hidden dependency.
To guarantee identical output across machines, matching or otherwise compatible R and package versions, RNG behavior, inputs, and graphics settings may be needed. Record these when exact comparison matters; different versions can still produce identical output in a particular case.
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
Consider the following R code.
reads <- c(31, 44, 18, 27, 52)
reads[reads > 25] <- 25
sum(reads)(a) What does reads > 25 evaluate to, before the second line runs? (b) What value does sum(reads) print, and what is reads after the second line? (c) Suppose instead that the second line had not been run. What would sum(reads > 25) have returned, and why does summing a comparison work at all?
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
A script imports a file and inspects it.
plots <- read.csv("data/plots.csv")
str(plots)The output is:
'data.frame': 60 obs. of 4 variables:
$ plot_id : chr "P01" "P02" "P03" "P04" ...
$ treatment: chr "control" "control" "amended" "amended" ...
$ height_cm: chr "14.2 cm" "16.8 cm" "19.1 cm" "15.5 cm" ...
$ leaves : int 8 11 13 9 ...Running mean(plots$height_cm) produces a warning rather than a number.
(a) Explain precisely why height_cm is a character column while leaves is an integer column. (b) Write one line of R that produces a numeric height column called height. (c) State why str() should be run before any summary calculation, and give one line that verifies the conversion in part (b) succeeded for every row.