r-quiz

R
en
quiz
Published

March 11, 2024

1 Define a variable

Define in R the variable age and assign the value 42.

age <- 42

Note that spaces here are not mandatory, but useful.

2 Define a variable as a string

Define in R the variable name and assign the value me.

name <- "me"

3 Define a variable by another variable

Define in R the variable name and assign the variable age.

name <- age

4 Call a function

Ask R what today’s date() is, that is, call a function.

date()
[1] "Mon Mar 11 12:38:04 2024"

5 Define a vector

Define in R a vector x with the values 1,2,3 .

x <- c(1, 2, 3)

6 Sum up vector

Define in R a vector x with the values 1,2,3 . Then sum up its values.

x <- c(1, 2, 3)
sum(x)
[1] 6

7 Vector wise computation

Square each value in the vector x.

x^2
[1] 1 4 9

8 Vector wise computation 2

Square each value in the vector x and sum up the values.

sum(x^2)
[1] 14

9 Compute the variance

Compute the variance of x using basic arithmetic.

 x <- c(1, 2, 3)

sum((x - mean(x))^2) / (length(x)-1)
[1] 1
 # compare: 
var(x) 
[1] 1

10 Work with NA

Define the vector y with the values 1,2,NA. Compute the mean. Explain the results.

y <- c(1, 2, NA)
mean(y)
[1] NA

NA (not available, ie., missing data) is contagious in R: If there’s a missing element, R will assume that something has gone wrong and will raise a red flag, i.e, give you a NA back.