| This verb | Does this | Example | Notes |
|---|---|---|---|
| arrange | sorts or orders the by the columns listed | arrange ( last_name, first_name) | use arrange (desc (col name) ) to go from highest to lowest |
| select | Picks out columns to use in this chunk | select ( newname=last_name, first_name, salary) select (1:3) to get the first three columns |
use back-ticks to enclose multi-word column names; generally use it last in the list of commands because you have to have selected something before you can use it anywhere else. Names are case-sensitive. You can rename at the same time. |
| filter | Picks out rows to use in this chunk | filter (last_name == “Batts”) | Case-sensitive. Don’t forget the double-equals. Use != for “not equals” or ! before any condition to negate it. |
| mutate | create new columns from old ones | mutate ( diff = salary2021 - salary2020, pct_diff = diff / salary2020 * 100 ) |
See below for common functions and formulas used in mutate statements |
| group_by | creates piles out of the data, usually used with summarise. | group_by (last_name) | If you group by more than one column, the subsequent commands work on the next level up. (See below). To makes sure that it goes back to normal, use group_by (last_name, first_name, .groups=“drop”) |
| summarise | computes summary statistics like the count, sum, or median of values | summarise ( no_of_rows = n(), sum_of_values = sum(salary, na.rm = TRUE), first_row_found = first(salary) | Your resulting dataset will include only the group_by and these summary columns, no other details. Using it without a group_by will return one row with the statistics for the whole data frame. |
| count | shortcut for group_by / summarise (n()) | count(last_name) | creates a group for each last_name, and counts their instances. |
For all of these verbs, the beginning parentheses has to be on the same line as the verb.
select
(last_name)
It has to be
select (
last_name)
… if you want to split lines.
%>% is the pipe. It means “and then do the next thing”. It must be on a line before the next command.
<- creates a new variable in your Environment. Use this to save the output of your code chunks to use in later ones.
There are a gazillion reasons for this error, but R is basically telling you that it doesn’t have access to something you’re asking for. Common reasons for it are:
This can mean you have a hanging pipe . (There’s nothing after it.) Once you fix this, you often have to run the code chunk twice – once to clear out the memory, so to say, and again to start fresh.
It can also mean you have mis-matched parentheses.
Again, this usually refers to not loading the tidyverse in your setup chunk, or not running that chunk in every session.
Just what it sounds like - you have opened or closed a parentheses without a matching one.
This can come from any error in the document, and it’s hard to troubleshoot. Some hints:
error=TRUE to the part in the setup just after where you see echo=TRUE in our template.Common problems include:
Functions can be used inside of the verbs so you’re not stuck with just what you see. A function is a sub-verb. It requires a noun (column) to work on, and some arguments ( specific instructions) to make them work. The “help” on these is almost impossible to read. Instead, try googling it for examples or ask for help. Many require libraries to be loaded.
You can look some of these up, but just know they exist in case you need them and ask for help:
toupper( col_name ) or tolower( col_name ) : Convert to all lower or upper case.
str_detect( col_name, pattern) : Instead of == so you can look for several things at once or inexact matches (See below)
splitting or extracting functions: These are ways to split apart phrases into more than one column, or pull out key phrases. They’re hard to use, but they exist. Get help if you want to do this.
This shouldn’t be so hard. In other languages, there are “wildcards” to look for phrases and you can specify whether it’s case-sensitive. Not in R.
Use str_detect() within a filter (to pick out rows that match) or mutate (to create new variables if there is a match). It detects whether or not a string or text variable contains what you’re looking for. It’s very powerful because it uses regular expression. At its simplest:
str_detect (what column are you looking at?,
what pattern should it have?)
This will still be case-sensitive. To fix that:
filter ( str_detect ( tolower(col_name), "phrase")
patterns include :
.We’ll have a module on regular expressions later on. Let me know if you need to use one now, because they’re very very powerful.
An NA in the data propagates. That means that anything that is NA will create NA in anything it touches, including sums.
filter (is.na(col_name))sum(col_name, na.rm=TRUE). This treats them as zero, which could be a problem if you combine with a count.mutate ( new_col = replace_na (old_col, 0) )if_then()Two possible outcomes: true or false – there’s no in between, and NA is always false.
The form is:
new_col = if_then ( condition, output if true, output if false)
case_when()When there can be many possible outcomes, or you want to do something else with NA. The first condition that matches is the one that wins if more than one is true.
The form is:
new_col = case_when ( condition ~ output if true,
condition ~ output if true,
TRUE ~ output for everything else)`
For data that starts as a spreadsheet or a CSV or other text file, use
read_csv (comma-separated text file. Very common)
read_tsv (tab-separated text file)
read_delim (text file delimited by something else)
read_excel (an XLSX file. It won't work on very old spreadsheets)
readRDS() A native R file saved as an .RDS file .
There is probably a library or a function that will read almost any data you run into.
Use the lubridate library to deal with dates and times. We’ll go over it more in detail, but here’s how to convert a text date into a real date using the mdy() function.
my_date = mdy(“1/24/2021”) will turn it into a date.
Part of the janitor library, converts all names to lower case with no spaces (which are converted to “_“)