Concepts for R
R is a programming language and environment primarily used for statistical computing and graphics. Developed by Ross Ihaka and Robert Gentleman in the early 1990s, R provides a wide range of statistical and graphical techniques, including linear and nonlinear modeling, time-series analysis, and clustering. R's syntax is optimized for data analysis tasks, with built-in support for data manipulation, visualization, and statistical modeling. Key features include an extensive collection of packages contributed by the R community through the Comprehensive R Archive Network (CRAN), allowing users to access a vast array of specialized tools and algorithms for various statistical and data analysis tasks. R's popularity in academia, research, and data-driven industries such as finance and healthcare is attributed to its flexibility, robustness, and the rich ecosystem of packages available for data analysis and visualization.
Print Text
print('Hello World!') print("Hello World!")
Comments
# one line comment # multi # line # comment
Variables
carCount <- 2 name <- "Joe" isPurple <- TRUE
Data Types
carCount <- 2 age <-15 seaLevel <- -10000 usBudget <- 11000000000 lightSpeed <- 11799312874 myGPA <- 3.45 piValue <- 3.14159265 lastLetter <- "Z" isMale <- TRUE myName <- "Joe"
Math Op
carCount <- 6; truckCount <- 3; total <- carCount + truckCount print(total) subtract <- carCount - truckCount print(subtract) multiple <- carCount * truckCount print(multiple) divisible <- carCount / truckCount print(divisible) # performs division and gets remainder which is 0 modulo <- carCount %% truckCount print(modulo)
Math Functions
power <- 3 ^ (6) print(power) root <- sqrt(16) print(root) floorVal <- floor(3.14) print(floorVal) ceilVal <- ceiling(4.3) print(ceilVal) roundVal <- round(3.4) print(roundVal) # random number from 0 to 100 ranNum <- sample(0:100, 1) print(ranNum)
If/Else
carCount <- 6; if (carCount > 3) { print("More than three cars"); } else if(carCount == 3) { print("Equal to three cars"); } else { print("Less than three cars"); }
Ternary
carCount <- 3 result = if(carCount > 2) "Yes" else "No" print(result)
Switch
carCount <- 3 result <- switch(carCount, "1"="One car", "2"="Two cars", "3"="Three cars", "More than three") print(result)
Functions
handleCars <- function(cars, wheels) { total <- cars * wheels return (total) } result <- handleCars(3, 4) print(result)
Interpolation
name <- "Joe" car <- "Mazda" result <- sprintf("%s drvies a %s", name, car) print(result)
Type Casting
squareA <- function(length) { result <- length ^ 2; return (as.character(result)); } squareL <- "4"; convertedVal <- as.numeric(squareL); area <- squareA(convertedVal); print(area)
Date and Time
# date and time date = Sys.time() print(date) # epoch time milliseconds = as.numeric(as.POSIXct(date)) print(milliseconds) # current year year = format(date, "%Y") print(year) # current month month = format(date, "%m") print(month) # formatted date formatted = format(date, "%m/%d/%Y") print(formatted)
Classes
Cars <- setRefClass("Cars", fields = list(carList = "list"), methods = list( addCar = function(car) { carList <<- append(carList, car) }, removeFirst = function() { carList <<- carList[-1] } ) ) newList <- Cars() newList$addCar("Honda") newList$addCar("Mazda") newList$addCar("Toyota") newList$removeFirst() # direct reference only firstCar <- newList$carList[1] print(firstCar)
Inheritance
User <- setRefClass("User", fields = list( username = "character", password = "character" ) ) Admin <- setRefClass("Admin", fields = list( id = "character" ), contains = "User" ) newAdmin <- Admin( username = "alpha0", password = "pw1", id = "1FE" ) print(newAdmin$username) print(newAdmin$id)
Method Overload
// No Native Support or Implementation
Abstract Class
// No Native Support or Implementation // Use the R6 library
Static Class
// No Native Support or Implementation
Arrays/Lists
names <- list("Joe", "Alex", "Bob") names[2] = "Tom" name = names[2] numItems = length(names) print(name) print(numItems)
Array Methods
cars <- list("Honda", "Mazda", "Toyota") # number of array elements print(length(cars)) # check to see that element is in array print("Mazda" %in% cars) # remove the numbered element cars[-1] print(cars[1]) # add Ford to array append(cars, "Ford") print(cars[3])
Concatenation
carsListKr <- c("Kia", "Hyundai", "Daewoo") carsListJp <- c("Honda", "Mazda", "Toyota") combined = cbind(carsListKr, carsListJp) print(combined[1]) print(combined[4])
Sort Method
ages <- c(5, 3, 1, 6, 7, 4, 19) result <- sort(ages) print(result)
Objects
User <- setRefClass("User", fields = list( first = "character", last = "character", age = "numeric", retired = "logical", carBrands = "list", fullName = "character" ), methods = list( setFullname = function() { fullName <<- sprintf("%s %s", first, last) } ) ) brands <- list("Mazda", "Toyota"); user <- new("User", first = "Joe", last = "Doe", age = 23, retired = FALSE, carBrands = brands ); user$setFullname() print(user$first) print(user$carBrands[1]) print(user$fullName)
Maps (Key/Value)
rm(list = ls()) # create the list carMap <- list() # Build up key value pairs carMap[[ "Joe" ]] <- "Toyota" carMap[[ "Bob" ]] <- "Mazda" carMap[[ "Tom" ]] <- "Ford" print(carMap$"Tom") carMap[["Tom"]] <- NULL print(carMap$"Tom" != NULL)
Sets
# no built in implementation # use external libraries
Stack
cars <- list() cars <- append(cars, "Mazda") cars <- append(cars, "Honda") cars <- append(cars, "Toyota") print(cars[length(cars)]) cars <- cars[-length(cars)] print(cars[length(cars)])
Queues
cars <- list() cars <- append(cars, "Mazda") cars <- append(cars, "Honda") cars <- append(cars, "Toyota") print(cars[1]) cars <- cars[-1] print(cars[1])
Linked List
Node <- setRefClass("Node", field = c( value = "character", "next" = "ANY" ) ) LinkedList = setRefClass("LinkedList", # allows for assigning values by reference field = c( head = "ANY" ), methods = list( add = function(value) { newNode <- Node( value = value, "next" = NULL ) if (is.null(head)) { head <<- newNode } else { current = head while (!is.null(current[["next"]])) { current = current[["next"]] } current[["next"]] = newNode } }, traverse = function() { current = head while (!is.null(current)) { print(current$value) current = current[["next"]] } } ) ) carList = LinkedList( head = NULL ) carList$add("Mazda") carList$add("Toyota") carList$add("Honda") carList$traverse()
Graphs
rm(list = ls()) Graph <- setRefClass("Graph", fields = list(graphMap = "list"), methods = list( addNode = function(val) { graphMap[[val]] <<- list() }, addVertices = function (node1, node2) { templist <- list() if(node1 %in% names(graphMap) == FALSE) { graphMap[[node1]] <<- list() } if(node2 %in% names(graphMap) == FALSE) { graphMap[[node2]] <<- list() } nodeOneArr = graphMap[[node1]] nodeTwoArr = graphMap[[node2]] graphMap[[node1]] <<- append( nodeOneArr, node2 ) graphMap[[node2]] <<- append( nodeTwoArr, node1 ) }, breadthTraverse = function(start) { queue <- list(start) visited <- list() visited[[start]] <- TRUE while(length(queue) > 0) { curVal = queue[1] print(curVal) queue <- queue[-1] tempArr = graphMap[[sprintf("%s", curVal)]] for(tempVal in tempArr) { if (tempVal %in% names(visited) == FALSE) { queue <- append(queue, tempVal) visited[[tempVal]] <- TRUE } } } }, depthTraverse = function(start) { stack <- list(start) visited <- list() visited[[start]] = TRUE while(length(stack) > 0) { curVal = stack[length(stack)] print(curVal); stack <- stack[-length(stack)] tempArr = graphMap[[sprintf("%s", curVal)]] for(tempVal in tempArr) { if (tempVal %in% names(visited) == FALSE) { stack <- append(stack, tempVal) visited[[tempVal]] <- TRUE } } } } ) ) newGraph <- Graph() newGraph$addNode("a") newGraph$addVertices("a", "b") newGraph$addVertices("a", "c") newGraph$addVertices("b", "d") newGraph$addVertices("b", "e") newGraph$addVertices("d", "f") newGraph$addVertices("d", "g") newGraph$addVertices("d", "h") newGraph$addVertices("e", "i") newGraph$addVertices("e", "j") newGraph$breadthTraverse("a") newGraph$depthTraverse("a")
For Loops
names <- list('Joe', 'Alex', 'Bob'); for (name in names) { print(name); }
While Loops
carList <- list("Mazda", "Toyota", "Honda") while(length(carList) > 0) { print(carList[1]) carList <- carList[-1] } print(length(carList))
Loop Breaks
cars <- list('Toyota', 'Honda', 'Mazda') i <- 0 for (car in cars) { if (car == "Honda") { result <- sprintf("Found at index %d", i) print(result) break } result <- sprintf("Visited index %d", i) print(result) i <- i + 1 }
Recursion
getSum <- function(arr) { if (length(arr) == 1) { return (arr[1]) } else { val <- as.numeric(arr[1]) arr <- arr[-1] secondVal <- getSum(arr) return(val + as.numeric(secondVal)) } } testArr <- list(1, 2, 4, 5) sum <- getSum(testArr) print(sum)
Regex Words
phrase <- "I am legend" pattern <- "\\w+" rg <- regexpr(pattern, phrase) result <- regmatches(phrase, rg) print(result)
Regex Numbers
phrase <- "I am 23" pattern <- "\\d+" rg <- regexpr(pattern, phrase) result <- regmatches(phrase, rg) print(result)
Regex Test
library(stringr) phrase <- "Bob Lee" pattern <- "Lee" result <- str_detect(phrase, pattern) print(result)
Regex Characters
phrase <- "##I am legend##" pattern <- "\\#+\\w+" rg <- regexpr(pattern, phrase) result <- regmatches(phrase, rg) print(result)