C1 - Sample Solution

Here you find the sample solution for the exercise sheet of chapter 1

R as a calculator

Task 1

Use R to do the following calculations:

### Solve the calculations

# 1
5+3
[1] 8
# 2
3-8
[1] -5
# 3
5*7
[1] 35
# 4
9/6
[1] 1.5
# 5
7^2
[1] 49
# 6
exp(5)
[1] 148.4132
# 7
log(9)
[1] 2.197225
# 8
5.56 + 4.73
[1] 10.29

Task 2

Assign a variable x the value of 5 and a variable y the value of 3.

# Variable x
x <- 5

# Variable y
y <- 3

Task 3

Create the variable z as the product of x and y and in a next step check the value of z.

# Create z by multiplying x and y
z <- x*y

# Check z
z
[1] 15

Task 4

Run the code line below:

# Run
w <- ((((25*(-13))/0.753))^2)*(-0.000466)

Use logical operators to check the following things:

# Is w exactly equal to 100?
w == 100
[1] FALSE
# Is w unequal to 50?
w != 50
[1] TRUE
# Is w smaller than 0?
w < 0
[1] TRUE
# Is w smaller or equal to -1?
w <= -1
[1] TRUE
# Is w larger than -70?
w > -70
[1] FALSE
# Is w larger or equal to -100?
w >= -100
[1] TRUE

Basic R programming

Task 5

Create a vector that contains the numbers 21, 28, 31, 23 and 45 and call this vector bmi.

# Create bmi vector
bmi <- c(21, 28, 31, 23, 45)

Task 6

Create a vector that contains the words “subject_1”, “subject_2”, “subject_3”, “subject_4” and “subject_5” and call this vector names.

# Create names vector
names <- c("subject_1", "subject_2", "subject_3", "subject_4", "subject_5")

Task 7

Check the types of the bmi and names vector.

# Check type of bmi
typeof(bmi) 
[1] "double"
# Check type of names
typeof(names)
[1] "character"

Task 8

Combine the two vectors names and bmi in a list and call this list bmi_data. Check out the content of this list by calling it.

# Combine the bmi and names vector in list called bmi_data
bmi_data <- list(names, bmi)

# Call the list
bmi_data
[[1]]
[1] "subject_1" "subject_2" "subject_3" "subject_4" "subject_5"

[[2]]
[1] 21 28 31 23 45