R Script Syntax
Last Updated 2019-04-23 by Adam Lu TODO: Put operators in a table format?
Variables
# Assign to a variable
var <- 3
var = 3
Arithmetics
# Arithmetics
num1 + num2
num1 - num2
num1 * num2
num1 / num2
# Compute the exponent of a number
num1 ^ exponent
# Compute the remainder of num1 devided by num2
num1 %% num2
# Missing entries
NA
Relations
# Relational operators
==
!=
<=
>=
<
>
#
|
&
Vectors
Assume myVec
is a vector:
# Create a vector by concatenation
myVec <- c(var1, var2, var3)
# Create a sequence vector
myVec <- seq(from = start, to = end, by = increment)
# Access the nth element of a vector
myVec[n]
# Select all but the nth element of a vector
myVec[-n]
# Access elements of a vector satisfying a condition
myVec[condition]
# Element-wise arithmetics
myVec1 + myVec2
myVec1 - myVec2
myVec1 * myVec2
myVec1 / myVec2
Matrices
# Create matrix from a vector
myMat <- matrix(data = myVec, ncol = 3)
myMat <- matrix(data = myVec, nrow = 2)
# Select the mth row of a matrix
myMat[m,]
# Select the nth column of a matrix
myMat[,n]
# Access the element at the mth row and nth column from a matrix
myMat[m, n]
Data Frames
# Create a data frame from vectors
myDf <- data.frame(var1 = vec1, var2 = vec2, var3 = vec3)
# Select a column from a data frame
var1 <- myDf$var1
var1 <- myDf[["var1"]]
Expressions
# Create an expression
myExpr <- expression(var1 ~ var2)
Strings
# Create a string
myStr <- "Beenhakker"
Lists
Assume myList
is a list:
# Create list from variables (do not have to be the same length)
myList <- list(name1 = value1, name2 = value2, name3 = value3)
# Access a value for a name-value pair from a list
value1 <- myList$name1
value1 <- myList[["name1"]]
# Create list from variable arguments
args <- myList(...)
Function definitions
# Anonymous functions
function (x) {...}
function (x) {x + 1} # adds 1 to the first argument
# Define a function called myFun1
# Note: arg1 is required
# arg2 is optional with a default defined
# ... (ellipses) are variable extra arguments
# The last output is returned
myFun1 <- function(arg1, arg2 = arg2Default, ...) {
# Blah
return(output)
}
# Define a function called myFun2
# Note: ... means there can be an indefinite number of arguments
# All arguments after ellipses must have default values
myFun2 <- function(..., arg1 = arg1Default) {
# Blah
}
Binary Operators
# Define a binary operator
"%myBinOp%" <- function(arg1, arg2) {
# Blah
}
# Use a binary operator
result <- first %myBinOp% second %myBinOp% third
Conditionals
# If else
if {
# Blah
} else {
# Bleh
}
# In one line
if (test_expression) "statement1" else "statement2"
Loops
# For loops
for (i in 1:5) {
# Blah
}
for (item in list) {
# Blah
}