This tutorial will teach you background knowledge on R. You’ll learn about:
First things first! Download these files into your working directory:
Open up Rstudio.
Start a new notebook file by selecting “File” -> “New File” -> “R Notebook”
Save the file as “yourname_week5.Rmd”. Delete the instructions starting from “This is an [R…”. For the different code below, insert it as R chunks. An R chunk is code placed after a line that starts with ` { r } `and ends before a line with `
`.
For this tutorial, you will be copying the code chunks below into your R notebook as R chunks.
Object: variable, function, data etc. What fills up your environment
print("Hello World")
Copy the above code into your console and press enter. Next, copy it as an R chunk into your notebook. Press play.
load("R_basics.Rdata")
sum(x)
plot(x,y)
require(limma)
source("helper.R")
Try it!
1 + 2
2/4
(4+5^7)/56
3 %% 5
log10(100)
x <- 1
y = 2
very_important_variable <- 0
not_very_important = 100
data <- 0
data <- 3
data <- x + y
data <- sqrt(x)
data <- rnorm(1000)
more_data <- 1000
data <- data + more_data
1
1.32545
5e9
'A'
'z'
"Yaaaas"
"Booo"
"Whatever"
c(1,3,5)
c('A', 'B', 'C')
c("Hello", "Goodbye")
1:100
rnorm(100)
rep(1,10)
seq(0,200,10)
my_seq <- seq(0,200,10)
my_seq[1]
my_seq[1] <- 1000
my_seq[3:6] <- c(30,20,40,36)
NOTE: in R, we count from 1 (not 0)
diag(10)
matrix(1:10, ncol=5, nrow=2)
cbind(1:10, 10:1)
rbind(1:10, 10:1)
A <- diag(5)
A[1,5] <- 9
A
my_seq <- seq(0,200,10)
my_seq[-10]
my_seq[-10:-20]
B <- 1:10
C <- "sex"
D <- list(A,B,C)
D[[1]]
$
names(D) <- c("A", "B", "C")
D$A
D[["A"]]
D[[4]] <- D
D[[4]][[4]] <- D
D[[4]][[4]][[3]]
D[[1]] <- NULL
my_list = list("a", "b", "c")
your_list = list("x", "y","z")
append(my_list, your_list)
E <- list()
sex <- c("male", "female", "male", "male", "female")
sex <- factor( sex, levels=c("male", "female"))
sex
sex[1] <- "female"
sex[2] <- "unknown" # This will cause an error!
sex # You should see the NA value
data.frame( x=1:10, y = rep("hello", 10) )
As R is an object-oriented (OO) language, there are also some OO systems (which we will not go through here). The most commonly used in bioinformatics related packages is the S4 class. For some advanced reading: http://adv-r.had.co.nz/S4.html.
?order
order
Some useful functions:
length(my_list) # returns the length of an object
sort(my_seq) # sorts a list, vector or matrix
ls() # lists all the objects in your environment
my_function <- function(arg1, arg2, ... ){
commands (or statements)
return(object)
}
dist
my_plot(my_seq) ```
https://posit.cloud/learn/cheat-sheets https://posit.cloud/learn/primers/1.2
Back to the homepage