5 Functions

5.1 Function Basics - an example using str()

Functions are the main way that you will handle or manipulate data. Something is a function if it is in the form functionname(arg1, arg2, …)

To see what a function does, and what arguments it requires, you can enter the function name into the help function, eg help(str)

5.2 Common (base) functions

5.2.3 Properties & Lookups

Length - The number of elements in an object

## [1] 1
## [1] 4
## [1] 11

Logic functions for different types of value

## [1] FALSE  TRUE FALSE FALSE
## [1] TRUE

Find the POSITION of the element with highest/lowest value

5.2.4 Transformation

Reverse elements in a vector

Format numbers to include comma separators - this converts numbers to characters

## [1] "1,000"  "1,500"  "20,000"

When a DataFrame/tibble has been created, various functions can be used to describe it, such as:

  • dim() # Shows number of rows and colums
  • length() # Number of columns
  • colnames() # The column names
  • head() # Displays first 6 rows
  • str() # variable name, type and example values

There are also some mathematical functions, including: * summary() # Summary statistics for numeric columns (mean, min, max, Q1, Q3) * colSums() # Sum of each column * colMeans() # Mean of each column

5.2.5 Other useful functions

Generate a number sequence

## [1] 1 2 3 4 5
## [1] 1 3 5

5.4 Lubridate - more date functions

Lubridate helps parse, convert, and extract information from dates.

## [1] 6
## [1] 14
## [1] April
## 12 Levels: January < February < March < April < May < June < ... < December
## [1] 2
## [1] 2017

5.5 Converting data to other formats

5.5.1 JSON

The RJSONIO package can convert R objects into JSON.
A vector/list will become a JSON array ["“,”“,”"]

## [1] "[      1,      2,      4,      8,     16 ]"

A dataframe or List will become a JSON object eg. {"“:[],”":[]}