Exercises programming in R

Albart Coster

Programming 1

Objects of class numeric

  1. Declare a vector n1 with 20 random numbers (you could use function sample for this).
  2. Copy elements at positions 1 to 10 to new vector n11. Copy elements at positions 11 to 20 to vector n12.
  3. Combine n11 and n12 into nnew.
  4. Challenge: copy element at the even positions from n1 to neven (use function seq and read about the by argument of this function).

Objects of class character:

  1. Declare fName with your first name and lName with your last name.
  2. Combine fName and lName into vector Name.
  3. Paste Name into pName with a space between your first name and your last name.

Matching and replacing:

  1. Test (1,2,3) occur in vector n1. If not, make them occur in n1.
  2. Obtain the indices where (1,2,3) occur in n1.
  3. Replace the elements of n1 where (1,2,3) occur with NA (NA is used in R for Not Available).

Splitting a character string:

  1. Split character string Name back into fName1 and lName1.
  2. Test if fName and fName1 are identical (hint: use the identical function).
  3. Split fName1 into single characters and count the number of characters.

End of exercises programming 1

Exercises programming 2

Matrices

  1. Create a square matrix object mat1 of three rows. The elements of mat1 should be NA.
  2. Fill the diagonal elements of mat1 with 1 and the off-diagonal elements with increasing numbers ( use function diag to obtain and replace the diagonals, and functions upper.tri and lower.tri to obtain and replace the off-diagonals of the matrix.
  3. Replace the elements of row 2 in mat1 with 2 times their value.
  4. Calculate the column and row sums of mat1.
  5. Make mat2 as the combination of two mat1 by row and mat3 as the combination by columns.

Data.frames

  1. Read about the ChickWeight dataset (?ChickWeight). Summarize this data.frame.
  2. Copy the subset of ChickWeight where Time == 0 to CW.
  3. Calculate the mean weight of the chicks at Time == 0.
  4. Calculate the mean weight of the chicks per diet (first know how many diets there are).
  5. Replace the chick ids with a unique name for each chick. If it does not work, have a look at what the Chick column in reality is.

Writing and reading data

  1. Write the ChickWeight data.frame into a *.csv file.
  2. Read the data into ChickWeight1 and compare if the two data.frames are identical.

End of exercises programming 2

Exercises programming 3

Iteration

  1. Calculate the standard deviation of weight at each moment and for each diet in the ChickWeight data (use function sd to calcute the standard deviation).
  2. Count the number of chicks at each timepoint in the ChickWeight data.
  3. Use function tapply to repeat the questions in the exercise above. If you did already, repeat the previous exercises using a loop.

End of exercises programming 3