Skip to content

2.RPrep

Lola-W edited this page Feb 15, 2023 · 1 revision

Objective: Get a basic working knowledge of R

Time estimated: 2 h; taken * h;

Date started: 2023-1-15 ; completed: 2023-1-12


Getting help

  • Using ?? or apropos("^med") *# ^/$ all functions that begin/end with the string*

Basics of R syntax

  • Predict

    7 %% 2# Modulo operation (remainder of integer division)7 %/% 2# Integer division
    
    TRUE&FALSE # Returns FALSE
    TRUE|FALSE # TRUE
    
    >!(FALSE | (! FALSE))
    FALSE
  • Task: Practice

    (lastNum<6 | lastNum > 10)
    (lastNum >= 10 & lastNum <20)
    (2 == (((lastNum/7- (((10*lastNum/7)%/%1)/10)) /100)%/%1)^(1/3))

R scalars and vectors

summary(myVec)[c("Max", "Min")] == summary(myVec)[c(2, 5)] # 2nd and 5th
summary(myVec)["Median"] == summary(myVec)[3]

Matrices and higher-dimensional objects

  • Use matrix()or array()put togerther with rbind() or cbind() (row or column)

  • dim() for new mattrix

    > dim(a) <- c(2,6)
    > a 
    			[,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    1    3    5    7    9   11
    [2,]    2    4    6    8   10   12
    
    m[3:4, 1:2] # submatrix: rows 3 to 4 and columns 1 to 2

Data frames & Subsetting

  • Recall from MGY441, grepl is logical
LPSdat[grepl("Il", LPSdat$genes) & grepl("ra", LPSdat$genes), 1:2]

Lists

( plasmidData <- read.table(
                    file.path("data_files","plasmidData.tsv"),
                    sep="\t",
                    header=TRUE,
                    stringsAsFactors = FALSE) )
# column 1 as rownames
rownames(plasmidData) <- plasmidData[ , 1]
  • Change row name
row.names(plasmidData)[4] <-pMAL-p5x
  • get all elements
lapply(plasmidDB, function(x) { return(x$ori) })

Control structures

  • Task: Practice

    count <- 0
    add <- 3
    res <- c()
    while(count<=3){
        res[count+1] <- (add - count)
        count <- count + 1
    }
    res[count+1] <- "Lift Off!"
    res
    
    txt <- c(txt, "Lift Off!") #alternative solution
💡 **Conclusion and outlook**: Finished R recap