Exercise 1: Solutions first part

Task 1.1

Assign the number 2 to an object a.

a <- 2

Task 1.2

Take the natural logarithm of a.

log_a <- log(a)
log_a
[1] 0.6931472

Task 1.3

Assign a new object using sin <- a.

sin <- a
sin
[1] 2

Task 1.4

What will be the output of sin(sin)? Try to predict the output before executing the code!

sin(sin)
[1] 0.9092974

No error here as R is smart enough to interpret the oobject with (...) as a function!

Task 1.5

Assign a new variable b with the value TRUE.

b <- TRUE
b
[1] TRUE

Task 1.6

What will be the result of 1 + b? Why?

result_1_plus_b <- 1 + b
result_1_plus_b
[1] 2

Explanation: In R, TRUE will b automatically casted to a numeric value of 1. So 1 + 1 = 2.

Task 1.7

What will be the result of sqrt(b)?

result_sqrt_b <- sqrt(b)
result_sqrt_b
[1] 1

Explanation: Since TRUE is 1 in numeric terms, sqrt(1) = 1.

Task 1.8

What is the value of b+b?

result_b_plus_b <- b + b
result_b_plus_b
[1] 2

Explanation: TRUE + TRUE is 1 + 1 = 2.

Task 1.9

Assign a new variable c with the value '1'.

c <- "1"
c
[1] "1"

Task 1.10

What will be the result of 1 + c? Why?

Explanation: This will result in an error because c is a character string and cannot be added to a numeric value.

# Next line will throw an error
# result_1_plus_c <- 1 + c

We could use the function as.numeric and try to make a numeric from it:

result_1_plus_c <- 1 + as.numeric(c)
result_1_plus_c
[1] 2