Statistical Methods with R

Data Types & Packages

Unit A · Chapter 03 · Lecture 03a

Developed by Jeffrey M. Girard

Roadmap: More Programming

  1. Strings

  2. Factors

  3. Packages

Strings

Strings

  • When talking to R, we need a way to distinguish
    • Object/function names (e.g., the mean function)
    • Text/character data (e.g., the word mean)
  • Strings are R’s way of storing text data
    • Strings can store any characters (no rules!)
    • Strings are created and displayed with quotes
  • R has great tools for working with strings
    • Strings can be collected into vectors
    • Special functions can transform strings

Form

name <- "text in quotes"

Example

name <- "John Doe"

Strings Need Quotation Marks

# Without quotes, R looks for an object named red
my_color <- red
Error:
! object 'red' not found
# With quotes, it is a string
my_color <- "red"
my_color
[1] "red"

Quotation marks are what separate a value from a name. Without them R goes looking for an object, which is why the error mentions one you never made.

Strings Can Hold Any Symbol

# Characters that are illegal in object names are fine inside a string
dye <- "red#40"
dye
[1] "red#40"
dyes <- c("red#40", "blue#02")
dyes
[1] "red#40"  "blue#02"

Inside quotes the naming rules no longer apply: spaces, #, and anything else are just characters. R only reads what is inside as text.

Pitfall: Math Does Not Work on Strings

dyes + 1
Error in `dyes + 1`:
! non-numeric argument to binary operator
mean(dyes)
Warning in mean.default(dyes): argument is not numeric or logical: returning NA
[1] NA

mean() does not stop with an error; it warns and hands back NA. A result that looks like an answer is easier to miss than a failure.

Functions That Do Work on Strings

# How many elements are in the vector?
length(dyes)
[1] 2
# How many characters are in each element?
nchar(dyes)
[1] 6 7
# Some functions only make sense for strings
toupper(dyes)
[1] "RED#40"  "BLUE#02"

length() counts elements whatever they are; nchar() and toupper() only mean anything for text. What a function accepts follows from its purpose.

Factors

Factors

  • Factors represent categorical data
    • Factors have multiple possible levels
    • Levels are discrete categories
    • Each case belongs to exactly one
  • Sometimes levels are numeric “codes”
    • e.g., 1=Drama, 2=Action, 3=Comedy
    • R needs to know these aren’t numbers!
    • We can give each level a label
    • Or we can just store the levels as strings

Form

factor(values)

Example

factor(c(1, 2, 1))

From Numeric Codes to a Factor

# Ask 10 kids to order 1: nuggets, 2: pizza, or 3: salad
food <- c(2, 2, 1, 2, 1, 2, 1, 1, 2, 2)

food2 <- factor(food)
food2
 [1] 2 2 1 2 1 2 1 1 2 2
Levels: 1 2
table(food2)
food2
1 2 
4 6 

factor() tells R these numbers are labels, not quantities. The Levels: line is how a factor prints, and R found only the values that actually occur.

Declaring Levels That Did Not Occur

# Nobody ordered salad, but 3 was always a possible answer
food3 <- factor(food, levels = c(1, 2, 3))
food3
 [1] 2 2 1 2 1 2 1 1 2 2
Levels: 1 2 3
table(food3)
food3
1 2 3 
4 6 0 

State the levels yourself and the count for salad is a meaningful 0 rather than a category that silently does not exist.

Labelling the Levels

food4 <- factor(food, levels = c(1, 2, 3),
                labels = c("nuggets", "pizza", "salad"))
food4
 [1] pizza   pizza   nuggets pizza   nuggets pizza   nuggets nuggets pizza  
[10] pizza  
Levels: nuggets pizza salad
table(food4)
food4
nuggets   pizza   salad 
      4       6       0 

levels are the values in your data; labels are what you want printed. Naming them here means never again looking up what 2 meant.

Pitfall: Levels are Not Labels

# levels must match what is IN the data; labels are what you want printed
food5 <- factor(food, levels = c("nuggets", "pizza", "salad"),
                labels = c(1, 2, 3))
food5
 [1] <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
Levels: 1 2 3

All <NA>: R searched the data for the string "nuggets" and found only the number 2. It does not error; it quietly returns missing values.

Levels Can Be Strings to Begin With

genre <- c("pop", "metal", "pop", "rock", "rap", "rap", "pop", "rock")

genre2 <- factor(genre)
genre2
[1] pop   metal pop   rock  rap   rap   pop   rock 
Levels: metal pop rap rock
table(genre2)
genre2
metal   pop   rap  rock 
    1     3     2     2 

With no levels given, R sorts the observed values alphabetically, which is rarely the order you want in a table or a plot.

Packages

Packages

  • Cookbooks are a great way to learn to cook
    • They contain lots of recipes and instructions
    • Browse an online bookstore for a cookbook
    • Order it to add it to your personal bookshelf
    • To use, pull the cookbook off the shelf
  • Packages are like cookbooks for R
    • They contain helpful functions and datasets
    • Browse an online repository for a package
    • Install it to add it to your personal library
    • To use, load the package from the library

Form

library("package")

Example

library("tidyverse")

Pitfall: A Function R Cannot Find

students <- c("mary anne", "BENjamin", "Lee")
students
[1] "mary anne" "BENjamin"  "Lee"      
str_to_title(students)
Error in `str_to_title()`:
! could not find function "str_to_title"

The stringr package has a function that fixes capitalization, but “could not find function” means R cannot find that name. Check the spelling first, then whether the function’s package is installed and loaded.

Installing a Package

  • RStudio > Extras pane > Packages tab > Install button
  • Or run it yourself:
install.packages("stringr")

Warning

Run this in the Console, never inside a Quarto document, since it would reinstall the package every time you render.

Installing is Not Loading

str_to_title(students)
Error in `str_to_title()`:
! could not find function "str_to_title"
library("stringr")

str_to_title(students)
[1] "Mary Anne" "Benjamin"  "Lee"      

Installing puts the package on your library shelf; it is still not in this session until you take it down with library(). Install once per computer (and again after upgrading R); load once per session.

Keeping Packages Updated

  • RStudio > Extras pane > Packages tab > Update button
  • Worth doing occasionally, but not in the middle of an analysis, since a package update can change results

Learning More: Vignettes

browseVignettes("stringr")

Many packages ship long-form articles showing how they are meant to be used, usually a better starting point than the help page for any one function. This opens a browser window, so run it in the Console too.