Resources for R
by Fredrik Daneby
Useful links
| The R-Project | [ https://www.r-project.org/ ] |
| The comprehensive R archive network | [ https://cran.r-project.org/ ] |
| Deep R programming | [ https://deepr.gagolewski.com/index.html ] |
| Advanced R | [ http://adv-r.had.co.nz/Introduction.html ] |
Snippets
Command to run scripts
$Rscript [filename].r
Hello world
# One way to print
"Hello world"
# Another way to print
print("Hello world again")
# A third way to print
msg <- "Hello world a third time"
msg
# A fourth way to print
cat("Hello", "world", "a fourth", "time\n")
Types
Build in types
name <- "Knautz"
age <- 15L
footsize <- 10.3
friends <- list("Janne","Bo","Lisa")
relatives <- c("Nisse","Maj","Tom")
schoolyears <- c(2020L, 2021L, 2022L)
scores <- c(10, 20, 30)
happy <- TRUE
numbers <- c(1,2,3,4)
nothing <- NULL
cat("Class:\n================================\n")
cat("name:\t\t", class(name), "\n")
cat("age:\t\t", class(age), "\n")
cat("footsize:\t", class(footsize), "\n")
cat("friends:\t", class(friends), "\n")
cat("relatives:\t", class(relatives), "\n")
cat("schoolyears:\t", class(schoolyears), "\n")
cat("scores:\t\t", class(scores), "\n")
cat("happy:\t\t", class(happy), "\n")
cat("nothing:\t", class(nothing), "\n")
cat("\nTypeof:\n==============================\n")
cat("name:\t\t", typeof(name), "\n")
cat("age:\t\t", typeof(age), "\n")
cat("footsize:\t", typeof(footsize), "\n")
cat("friends:\t", typeof(friends), "\n")
cat("relatives:\t", typeof(relatives), "\n")
cat("schoolyears:\t", typeof(schoolyears), "\n")
cat("scores:\t\t", typeof(scores), "\n")
cat("happy:\t\t", typeof(happy), "\n")
cat("nothing:\t", typeof(nothing), "\n")
Vectors
Basics
cat("A vector must contain objects of the same type:\n")
number <- c(10,20,30,40,50)
cat("number is: ", number, "\n")
cat("number class: ", class(number), "\n")
cat("number typeof: ", typeof(number), "\n")
cat("length of numbers: ", length(number), "\n")
cat("\n")
cat("By changing one oject in the vector to a character string, all objects \
in the vector changes to the same type:\n")
number[2] = "stringzor"
cat("number is: ", number, "\n")
cat("number class: ", class(number), "\n")
cat("number typeof: ", typeof(number), "\n")
cat("length of numbers: ", length(number), "\n")
cat("\n")
cat("Assigning a decimal numeric value to the character string vector is \
accepted but does not change the vector types back to numeric decimal?\n")
number[2] = 20L # <-- This will silently be converted
cat("number class: ", class(number), "\n")
cat("number typeof: ", typeof(number), "\n")
number[2]
cat("Single values are also vectors:\n")
single_number = 10L
single_number[1]
cat("Creating vector using : operator:\n")
series <- 1:50
print(series)
cat("Creating integer vector using seq.int():\n")
sequence <- seq.int(from = 1, to = 50, by = 1 )
sequence <- seq.int(1, 50, 1 )
print(sequence)
sequence2 <- seq(0,10, length.out = 5)
print(sequence2)
Operations on vectors
numbers <- c(1, 2, 3, 4, 5, 6, 7)
4 %in% numbers # %in% operator
numbers == check_numbers # position dependent
check_numbers <- c(2, 4, 1, 9, 7, 2, 1) # vectorized %in%
results <- (numbers %in% check_numbers) # not position dependent
results
new_numbers <- append(numbers, 8) # append (and assign)
sort(numbers) # sort
numbers <- sort(numbers) # Replace numbers
sort(new_numbers, decreasing=TRUE) # sort decreasing
new_numbers <- sort(new_numbers, decreasing=TRUE) # replace new_numbers
cat("numbers:", numbers, "\n")
cat("slice:\t", numbers[1:4], "\n") # slice operator
cat("head:\t", head(numbers, 3), "\n") # head function
cat("tail:\t", tail(numbers, 3), "\n") # tail function
ten_numbers <- c(10, 20, 30, 40, 50, 60, 70)
# operations on vectors are vectorized
results <- numbers + ten_numbers # vectorized addition
print(results)
results <- ten_numbers - numbers # you get the idea
print(results)
# Statistical functions used on vectors
cat("sum: ", sum(numbers), "\n")
cat("mean: ", mean(numbers), "\n")
cat("min: ", min(numbers), "\n")
cat("max: ", max(numbers), "\n")
cat("median: ", median(numbers), "\n")
# Tests on types
is.numeric(numbers) # FALSE
typeof(numbers[2]) # double by default
is.integer(numbers)
is.atomic(numbers) # TRUE
letters <- c('A', 'B', 'C', 'D')
is.numeric(letters) # FALSE
Indexing vectors
# Vector indexing
letters <- c('A', 'B', 'C', 'D', 'E') # a vector of characters
letters[3] # integer index 3
letters[-3] # all but integer index 3
letters[c(1,3,5)] # a list of indices to use
letters[c(1,3,5)] <- c('A', 'C', 'E') # assign to three indices
# Logical indexing
logical_letters <- c(TRUE, FALSE, TRUE, FALSE, TRUE)# a logical vector
letters[logical_letters] # produce element if TRUE
numbers <- c(1, 2, 3, 4, 5, 6, 7)
numbers > 3 # logical
larger_numbers <- numbers[numbers > 3] # logical indices used
larger_numbers
((numbers < 2) | (numbers > 3)) # more logics
selected_numbers <- numbers[((numbers < 2) | (numbers > 3))]
selected_numbers
# Names can be used for indexing vectors
ascii <- c(65, 66, 67, 68, 69)
letters <- c('A', 'B', 'C', 'D', 'E') # same as above
names(ascii)<-letters
ascii
ascii["C"] # access through name
# Same thing but different
(ascii <- c(A = 65, B = 66, C = 67, D = 68, E = 69 ))
ascii["C"]
# Use explicit function to change names. Will produce a copy
another_numbers <- setNames(numbers, c("G", "H", "I", "J", "K", "L", "M")
names(numbers)
names(another_numbers)
Arrays and matrices
a <-- array(1:4)
print(a)
m <-- matrix(1:6, nrow=2, ncol=3) # Create a 2x3 (row x column) matrix
print(m) # using 1,2,3,4,5,6. rows are filled first
a <-- array(1:6, c(2,3)) # same thing but different
print(a)
m_by_row <-- matrix(1:6, byrow=TRUE, nrow=2) # rows are filled first
print(m_by_row)
m_with_names <--
matrix(1:6, byrow=TRUE, nrow=2, dimnames=list(c("x", "y"), c("a", "b", "c")))
print(m_with_names)
Lists
Indexing and printing
A <- list(c(1L, 2L, 3L)) # A list with one numberic vector with three integers
B <- list(10L,20L,30L) # Three numeric vectors with one integer
C <- c(100L, 200L, 300L) # A vector that is not a list
cat("The first vector of A:\n")
print(A[1]) # Print the first and only vector
cat("The second vector of A:\n")
print(A[2]) # NULL
cat("The second element of the first vector of list A:\n")
print(A[[1]][[2]])
cat("\nThe first vector of B:\n")
print(B[1]) # Print the first vector of three
cat("The second vector of B:\n")
print(B[2])
cat("The first element of the second vector of list B:\n")
print(B[[2]][[1]])
# A better way to print lists
str(A)
str(B)
# Turn a list into an atomic vector
is.list(A)
vector_A <- unlist(A)
str(A)
str(vector_A)
Attributes
# Attributes are applicable to all object, not only lists.
# The function "structure" can be used to set attributes
values <- list(1L, 2L, 3L)
values_with_attributes <- structure(values, names=c("X", "Y", "Z"), text=c("ex", "why", "sed"))
attributes(values_with_attributes) # show all attributes
attr(values_with_attributes, "names") # show one attribute
attr(values_with_attributes, "text")
# The special "names" attribute. Can be set at creation of lists and vectors
named_list <- c(person1="Lars", person2="Kenneth", person3="Maja")
cat("Accessing element using names attribute:\n" )
named_list["person1"]
cat("\nPrinting names in named_list:\n")
names(named_list) # this does not work for custom attribs
cat("\nThe same with attr() function (specific attribute):\n")
attr(named_list, "names")
cat("\nThe same with attributes() function (all attributes):\n")
attributes(named_list)
# dimnames is also a special attribute
m_with_names <-
matrix(1:6, byrow=TRUE, nrow=2, dimnames=list(c("x", "y"), c("a", "b", "c")))
print(m_with_names)
# so is dim
a_with_dims <-
array(1:6, dim=c(2,3))
print(a_with_dims)
Lists of lists and access to members
# Lists of lists, names and access to list members
animals <- list(species=c("Aardvark", "Triceratops", "Cod", "Ant"), extinct=list(FALSE, TRUE, FALSE, FALSE))
cat("Summary of the animals list:\n")
str(animals)
cat("Named list members can be accessed using the currency sign $:\n")
print(animals$species) # class == list
print(animals$extinct) # class == list
cat("\n...or by using indices")
print(animals[1]) # class == list
print(animals[2]) # class == list
cat("\nValues in named list members can be accessed using indices:\n")
animals$species[1]
animals$extinct[1]
cat("\nUsing names, the currency sign can be used further:\n")
more_animals <- list(species=list(name="Mongoose", name="Crocodile", name="Megalodon"), exctinct=list(status=FALSE, status=FALSE, status=TRUE))
more_animals$species[1]$name
more_animals$species[2]$name
more_animals$species[3]$name
cat("\n...by using indices and [[:\n")
more_animals[[1]][1]
more_animals[[1]][2]
more_animals[[1]][3]
Command to run scripts
$Rscript [filename].r
Hello world
# One way to print
"Hello world"
# Another way to print
print("Hello world again")
# A third way to print
msg <- "Hello world a third time"
msg
# A fourth way to print
cat("Hello", "world", "a fourth", "time\n")
Types
Build in types
name <- "Knautz"
age <- 15L
footsize <- 10.3
friends <- list("Janne","Bo","Lisa")
relatives <- c("Nisse","Maj","Tom")
schoolyears <- c(2020L, 2021L, 2022L)
scores <- c(10, 20, 30)
happy <- TRUE
numbers <- c(1,2,3,4)
nothing <- NULL
cat("Class:\n================================\n")
cat("name:\t\t", class(name), "\n")
cat("age:\t\t", class(age), "\n")
cat("footsize:\t", class(footsize), "\n")
cat("friends:\t", class(friends), "\n")
cat("relatives:\t", class(relatives), "\n")
cat("schoolyears:\t", class(schoolyears), "\n")
cat("scores:\t\t", class(scores), "\n")
cat("happy:\t\t", class(happy), "\n")
cat("nothing:\t", class(nothing), "\n")
cat("\nTypeof:\n==============================\n")
cat("name:\t\t", typeof(name), "\n")
cat("age:\t\t", typeof(age), "\n")
cat("footsize:\t", typeof(footsize), "\n")
cat("friends:\t", typeof(friends), "\n")
cat("relatives:\t", typeof(relatives), "\n")
cat("schoolyears:\t", typeof(schoolyears), "\n")
cat("scores:\t\t", typeof(scores), "\n")
cat("happy:\t\t", typeof(happy), "\n")
cat("nothing:\t", typeof(nothing), "\n")
Vectors
Basics
cat("A vector must contain objects of the same type:\n")
number <- c(10,20,30,40,50)
cat("number is: ", number, "\n")
cat("number class: ", class(number), "\n")
cat("number typeof: ", typeof(number), "\n")
cat("length of numbers: ", length(number), "\n")
cat("\n")
cat("By changing one oject in the vector to a character string, all objects \
in the vector changes to the same type:\n")
number[2] = "stringzor"
cat("number is: ", number, "\n")
cat("number class: ", class(number), "\n")
cat("number typeof: ", typeof(number), "\n")
cat("length of numbers: ", length(number), "\n")
cat("\n")
cat("Assigning a decimal numeric value to the character string vector is \
accepted but does not change the vector types back to numeric decimal?\n")
number[2] = 20L # <-- This will silently be converted
cat("number class: ", class(number), "\n")
cat("number typeof: ", typeof(number), "\n")
number[2]
cat("Single values are also vectors:\n")
single_number = 10L
single_number[1]
cat("Creating vector using : operator:\n")
series <- 1:50
print(series)
cat("Creating integer vector using seq.int():\n")
sequence <- seq.int(from = 1, to = 50, by = 1 )
sequence <- seq.int(1, 50, 1 )
print(sequence)
sequence2 <- seq(0,10, length.out = 5)
print(sequence2)
Operations on vectors
numbers <- c(1, 2, 3, 4, 5, 6, 7)
4 %in% numbers # %in% operator
numbers == check_numbers # position dependent
check_numbers <- c(2, 4, 1, 9, 7, 2, 1) # vectorized %in%
results <- (numbers %in% check_numbers) # not position dependent
results
new_numbers <- append(numbers, 8) # append (and assign)
sort(numbers) # sort
numbers <- sort(numbers) # Replace numbers
sort(new_numbers, decreasing=TRUE) # sort decreasing
new_numbers <- sort(new_numbers, decreasing=TRUE) # replace new_numbers
cat("numbers:", numbers, "\n")
cat("slice:\t", numbers[1:4], "\n") # slice operator
cat("head:\t", head(numbers, 3), "\n") # head function
cat("tail:\t", tail(numbers, 3), "\n") # tail function
ten_numbers <- c(10, 20, 30, 40, 50, 60, 70)
# operations on vectors are vectorized
results <- numbers + ten_numbers # vectorized addition
print(results)
results <- ten_numbers - numbers # you get the idea
print(results)
# Statistical functions used on vectors
cat("sum: ", sum(numbers), "\n")
cat("mean: ", mean(numbers), "\n")
cat("min: ", min(numbers), "\n")
cat("max: ", max(numbers), "\n")
cat("median: ", median(numbers), "\n")
# Tests on types
is.numeric(numbers) # FALSE
typeof(numbers[2]) # double by default
is.integer(numbers)
is.atomic(numbers) # TRUE
letters <- c('A', 'B', 'C', 'D')
is.numeric(letters) # FALSE
Indexing vectors
# Vector indexing
letters <- c('A', 'B', 'C', 'D', 'E') # a vector of characters
letters[3] # integer index 3
letters[-3] # all but integer index 3
letters[c(1,3,5)] # a list of indices to use
letters[c(1,3,5)] <- c('A', 'C', 'E') # assign to three indices
# Logical indexing
logical_letters <- c(TRUE, FALSE, TRUE, FALSE, TRUE)# a logical vector
letters[logical_letters] # produce element if TRUE
numbers <- c(1, 2, 3, 4, 5, 6, 7)
numbers > 3 # logical
larger_numbers <- numbers[numbers > 3] # logical indices used
larger_numbers
((numbers < 2) | (numbers > 3)) # more logics
selected_numbers <- numbers[((numbers < 2) | (numbers > 3))]
selected_numbers
# Names can be used for indexing vectors
ascii <- c(65, 66, 67, 68, 69)
letters <- c('A', 'B', 'C', 'D', 'E') # same as above
names(ascii)<-letters
ascii
ascii["C"] # access through name
# Same thing but different
(ascii <- c(A = 65, B = 66, C = 67, D = 68, E = 69 ))
ascii["C"]
# Use explicit function to change names. Will produce a copy
another_numbers <- setNames(numbers, c("G", "H", "I", "J", "K", "L", "M")
names(numbers)
names(another_numbers)
Arrays and matrices
a <-- array(1:4)
print(a)
m <-- matrix(1:6, nrow=2, ncol=3) # Create a 2x3 (row x column) matrix
print(m) # using 1,2,3,4,5,6. rows are filled first
a <-- array(1:6, c(2,3)) # same thing but different
print(a)
m_by_row <-- matrix(1:6, byrow=TRUE, nrow=2) # rows are filled first
print(m_by_row)
m_with_names <--
matrix(1:6, byrow=TRUE, nrow=2, dimnames=list(c("x", "y"), c("a", "b", "c")))
print(m_with_names)
Lists
Indexing and printing
A <- list(c(1L, 2L, 3L)) # A list with one numberic vector with three integers
B <- list(10L,20L,30L) # Three numeric vectors with one integer
C <- c(100L, 200L, 300L) # A vector that is not a list
cat("The first vector of A:\n")
print(A[1]) # Print the first and only vector
cat("The second vector of A:\n")
print(A[2]) # NULL
cat("The second element of the first vector of list A:\n")
print(A[[1]][[2]])
cat("\nThe first vector of B:\n")
print(B[1]) # Print the first vector of three
cat("The second vector of B:\n")
print(B[2])
cat("The first element of the second vector of list B:\n")
print(B[[2]][[1]])
# A better way to print lists
str(A)
str(B)
# Turn a list into an atomic vector
is.list(A)
vector_A <- unlist(A)
str(A)
str(vector_A)
Attributes
# Attributes are applicable to all object, not only lists.
# The function "structure" can be used to set attributes
values <- list(1L, 2L, 3L)
values_with_attributes <- structure(values, names=c("X", "Y", "Z"), text=c("ex", "why", "sed"))
attributes(values_with_attributes) # show all attributes
attr(values_with_attributes, "names") # show one attribute
attr(values_with_attributes, "text")
# The special "names" attribute. Can be set at creation of lists and vectors
named_list <- c(person1="Lars", person2="Kenneth", person3="Maja")
cat("Accessing element using names attribute:\n" )
named_list["person1"]
cat("\nPrinting names in named_list:\n")
names(named_list) # this does not work for custom attribs
cat("\nThe same with attr() function (specific attribute):\n")
attr(named_list, "names")
cat("\nThe same with attributes() function (all attributes):\n")
attributes(named_list)
# dimnames is also a special attribute
m_with_names <-
matrix(1:6, byrow=TRUE, nrow=2, dimnames=list(c("x", "y"), c("a", "b", "c")))
print(m_with_names)
# so is dim
a_with_dims <-
array(1:6, dim=c(2,3))
print(a_with_dims)
Lists of lists and access to members
# Lists of lists, names and access to list members
animals <- list(species=c("Aardvark", "Triceratops", "Cod", "Ant"), extinct=list(FALSE, TRUE, FALSE, FALSE))
cat("Summary of the animals list:\n")
str(animals)
cat("Named list members can be accessed using the currency sign $:\n")
print(animals$species) # class == list
print(animals$extinct) # class == list
cat("\n...or by using indices")
print(animals[1]) # class == list
print(animals[2]) # class == list
cat("\nValues in named list members can be accessed using indices:\n")
animals$species[1]
animals$extinct[1]
cat("\nUsing names, the currency sign can be used further:\n")
more_animals <- list(species=list(name="Mongoose", name="Crocodile", name="Megalodon"), exctinct=list(status=FALSE, status=FALSE, status=TRUE))
more_animals$species[1]$name
more_animals$species[2]$name
more_animals$species[3]$name
cat("\n...by using indices and [[:\n")
more_animals[[1]][1]
more_animals[[1]][2]
more_animals[[1]][3]