Introduction to Biological Data Analysis


TP 2: Data structures in R

Prof. Patrick Meyer

BioSys Lab - Université de Liège

Matrices

  1. Let y <- matrix(45:64, nr=5, byrow=TRUE)
    What will be displayed if we enter the following lines of code?
      > y[1,]
      > y[3:4,3:4]
      > y[-c(2,3),-c(1,4)]
      > cbind(y,c(2,3,5,8,13))
    

  2. Write a code that returns a matrix with 5 columns, having numbers from 10 to 19 in the two first lines and numbers from 50 to 59 in the two last lines.
    1. Add to this matrix two lines with numbers from 90 to 99.

    2. Remove the third column.
  3. Return a 4X4 matrix with only ones in it.

Functions on vectors and matrices

Given the following functions (use the help command if needed), sum(), prod(), t(), sqrt(), log(), apply(), min(), max(), sort(), paste(), rank(), which(), length(), print().

  1. Write a function that returns a vector of two elements the minimum and the maximum of another vector.

  2. Write a function that returns a vector made of the square roots of the $n$ biggest elements of another vector, but in decreasing order.

  3. Write a function that receives a vector and a number $n$, denoting the index of an element in a vector, and that returns a sentence with the value of $n$th element.
    for example, with $n=3$ and the vector $c(1.618, 2.716, 3.141)$, this function returns: "the 3d element of the vector is 3.141".

  4. Write a function that returns "OK" if a square matrix $A$ is symetric and else displays "KO".

    Reminder : a matrix $A_{ij}$ ($i$ from $1$ to $n$, $j$ from $1$ to $n$) of size $n$, is symetric if it is equal to its transpose, i.e. :


    \begin{displaymath}
\forall i,j : 1 \leq i,j \leq n : A_{ij}=A_{ji}
\end{displaymath}

  5. Write a code that returns a vector of square roots of the sum of the elements of each column of a matrix.
  6. Write a code that returns the sum of the logarithms (in base 2) of the product the elements of each line of a matrix.

Factors

  1. What happens when we type:
      > z <- factor(c(0,1,1,0,0,1,1))
      > levels(z) <- c("malade","saine")
      > z
    
  2. Convert the following factor in numeric f <- factor(c(0.1,0.9,3.14,1.618,0.5,1))

List

  1. If:
     > a <- list(valeurs=rep(c(1,2),3), motif=c("acgt","tgca") )
    

    What happens when we type the following lines (to do mentally):
     > a[[1]]
     > a[[2]][2]
     > a$motif
     > a$valeurs[3]
    

  2. Write a function that computes the number of numeric in a given list, for example in the list list("HeLLO",32,"every",3.14,"body","yeah"), the function should return 2.