Working with Data in R
Working with Data in R: Import, Inspect, Subset, Transform, Export
Know what you are holding
Almost every avoidable mistake in R data work comes from being wrong about the type of an object rather than about the analysis. Four structures cover most of it:
- Vector: one dimension, one type. Mixing types silently coerces everything to the most permissive one, so a single stray character value turns an entire numeric vector into character.
- Matrix: two dimensions, still one type throughout.
- Data frame: a list of equal-length columns, each with its own type. This is what tabular data should be.
- List: arbitrary elements of arbitrary types and lengths.
The first command after any import should be str(d). It prints the object's class, its dimensions, and for each column the column's type and first few values.
That single line catches the two problems that cause most downstream confusion: a numeric column that arrived as character, and a column that became a factor when it should not have.
Importing
read.csv("readings.csv") returns a data frame. Since R 4.0.0 the default for stringsAsFactors is FALSE, so text columns stay character unless you ask otherwise, useful to know, because older tutorials assume the opposite default and their advice no longer applies.
Missing values need declaring at import. Files often mark them with a sentinel such as -999 or the word NULL. R does not know these are missing, so:
d <- read.csv("readings.csv", na.strings = c("NA", "NULL", "-999"))Skip this and one of two things happens. A numeric column containing NULL arrives as character, because a character value forces the whole column to character. Or a column containing -999 arrives as numeric and the sentinel is silently treated as a measurement.
Treating it as a measurement can distort summaries, including means and standard deviations, and plots that include that row; summaries of unaffected subsets, such as group A in the assay example, remain unchanged.
Inspecting
dim(d), nrow(d) and ncol(d) give shape. head(d) shows the first rows. summary(d) gives a type-dependent summary of each column and reports NA counts for types such as numeric and factor columns.
To count missing values reliably for every column, use colSums(is.na(d)); for one column, use sum(is.na(d$ph)).
Use is.na(x) and never x == NA: comparison with NA returns NA, not TRUE or FALSE, so the test fails silently rather than erroring.
Subsetting
The two-index form d[rows, cols] is the one to internalise: rows first, columns second.
d[d$temp > 30, c("site", "temp")]When temp contains no missing values, this selects the rows where temp exceeds 30 and keeps two columns.
If temp is missing for a row, d$temp > 30 is NA for that row; using that NA as a row index produces an all-NA result row rather than a confirmed match. When only confirmed matches are required, exclude missing values explicitly:
d[!is.na(d$temp) & d$temp > 30, c("site", "temp")]Three traps sit close by. A single index, d[x], selects columns, not rows. Forgetting the comma is therefore not a typo that errors but a different operation. And d$temp > 30 on its own is just a logical vector, not a subset.
Missing values in calculations
Arithmetic propagates NA by design: if one value is unknown, so is the mean. Ask explicitly to drop them.
Worked example. Suppose d$ph holds the five values 4.2, 7.8, 6.0, NA, 9.0. Then mean(d$ph) returns NA. With the missing value dropped,
The denominator is the count of values actually used, which is 4, not 5. That is the arithmetic point worth holding on to: na.rm = TRUE changes the divisor as well as the sum.
Factors and a coercion that bites
A factor stores its values as integer codes into a table of levels.
When levels is not supplied, factor(x) normally constructs the levels from the sorted unique non-missing values of x; an explicitly supplied levels argument can also include values that never occur in the data, and a missing observation stays NA rather than becoming a level unless you ask for that explicitly.
When the underlying values are character, that sort is a string sort.
y <- factor(c("3", "12", "7"))String sorting compares character by character, so "12" comes before "3" because "1" precedes "3". The levels are "12", "3", "7" in that order, and the stored codes are 2, 1, 3.
Now as.numeric(y) returns those codes, 2 1 3, not the numbers 3, 12 and 7.
The function is doing exactly what it is documented to do, returning the integer representation, and it is doing it silently, which is why this produces plausible-looking nonsense rather than an error. The fix is to go through character first:
as.numeric(as.character(y))which recovers 3 12 7.
Transforming and summarising
Add or replace a column by assignment: d$temp_f <- d$temp * 9/5 + 32. Summarise by group with the formula interface:
aggregate(temp ~ site, data = d, FUN = mean)The formula interface drops rows with missing values in the variables it uses before computing, which is usually what you want, but it means the group sizes behind the result may differ, so check them rather than assuming they match.
Exporting
means <- aggregate(temp ~ site, data = d, FUN = mean)
write.csv(means, "means.csv", row.names = FALSE)Without row.names = FALSE, R writes the row names as an unnamed first column. Reading that file back produces a spurious column called X, and a file that survives a few such round trips accumulates X, X.1 and so on. Set the argument every time.
A data frame readings has 250 rows. For its numeric column ph:
- sum(is.na(readings$ph)) returns 37;
- sum(readings$ph, na.rm = TRUE) returns 1725.3.
What value does mean(readings$ph, na.rm = TRUE) return? Give the answer to two decimal places.
A data frame readings has the columns site, date, temp and ph. A student wants a data frame containing only the rows where temp is greater than 30, and only the columns site and temp.
Assume readings$temp contains no missing values.
Which expression does that?