Go to importing data

Go to summarising data

Go to making figures

Basic R operations, data frames, functions and packages

Exercise 1. Assign the numeric 3 to an object called a.

Solution Ex. 1


Exercise 2. What are the differences between these operations?

a <- 3
a = 3
3 -> a
3 = a

Try to explain your results.

Solution Ex. 2


Exercise 3. Combine the numeric values 3, 5, 6, 7 in a vector.

Solution Ex. 3


Exercise 4. Print the second value from your vector.

Solution Ex. 4


Exercise 5. Change the second value of your vector to 23.

Solution Ex. 5


Exercise 6. A parameter can be regarded as a constant in a given situation but can take different values in other situations. The benefit of working with parameters is that we can use the name of the parameter to describe for example mathematical operations.

Write code that corresponds to the following equation:

\[a = \frac{beta}{alpha}\]

given that \(beta = 3\) and \(alpha = 6\).

Solution Ex. 6


Exercise 7. What is the problem with the following operation:

vector_a <- c(3, 5, 2, 7, 9)

vector_b <- c(3, 3)

vector_a * vector_b


And how is this correct?

vector_c <- c(3, 5, 2, 7)

vector_d <- c(3, 2)

vector_c * vector_d

How do R calculate the second situation?

Solution Ex. 7


Exercise 8. A data frame is basically multiple vectors of data stacked in columns. Create a data frame by hand that corresponds to the table below.

ID Age Sex Performance Body_mass
id1 24 M 250 82
id2 25 F 180 65
id3 22 F 187 55
id4 26 F 210 59
id5 25 M 205 75
id6 29 M 199 89
Solution 8


Write code to: 1. return the first row in the data frame 2. create a new variable calculated as Performance per Body mass 3. print the the new variable from the data frame

Solution 9.1


Solution 9.2


Solution 9.3


Exercise 10. We can use functions to calculate mean, standard deviation, minimum and so on. Calculate the mean and standard deviation of Performance and Body mass. Store the results in a new data frame.


Solution 10


Exercise 11. We will be using several packages during the course. Install the follwing packages using the install.package() function:

Package
dplyr
tidyr
readxl
ggplot2

Solution 10