Introduction

There are a variety of useful functions in R. Below is a brief listing.

Using a function in a library

Some functions live in a different library. In this page, these are shown with the library name in front, such as readr::parse_integer(). You can run these using two different methods:

Method 1: Single-line

# Option 1: include the package name before the function name
readr::parse_integer(c('1', '2'))
## [1] 1 2

Method 2: Load library first

# Option 2: load the library, and then use the function
library(readr)

parse_integer(c('1', '2'))
## [1] 1 2

Math functions

  • median()/mean()/max()/min()/sum()
  • abs() - absolute value
  • round() - rounds 1.2 to 1
  • seq(from, to, increment) - returns a sequence from -> to (skipping every increment)
  • rep(x, times) - return a new vector of x, repeated times.

In the readr library:

  • readr::parse_integer(): turns “1” into 1
    • You can also specify what values to interpret as NA
    • parse_integer( x = c('1', '2', 'X', '?'), na = c('?', 'X'))

Text functions

  • paste0(text1, text2, ...): combine text values
  • paste(text1, text2, ..., sep = ',' ): combines text, split with sep

Tables

  • View(data): opens data in a nice gui. Note that it is capitalized!
  • names(data): what are the field names of the data?

Vectors/Lists

  • sort()/rev(): order items in a vector
  • vector_a <- append(vector_a, new_item_or_vector_of_items): create a new vector with the additional items
  • unlist(): turn a list into a vector

Graphics

  • plot(): create a basic x/y plot

Statistics

  • table(): create a crosstab
  • cor(): calculate correlation

Types

  • is_*(): test for types (convert * to integer, etc…)
  • as_*(): convert a type

Application problem

See problems on GitHub