<- 42 age
r-quiz
1 Define a variable
Define in R the variable age
and assign the value 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
.
<- "me" name
3 Define a variable by another variable
Define in R the variable name
and assign the variable age
.
<- age name
4 Call a function
Ask R what today’s date()
is, that is, call a function.
date()
[1] "Tue Oct 8 09:38:13 2024"
5 Define a vector
Define in R a vector x
with the values 1,2,3 .
<- c(1, 2, 3) x
6 Sum up vector
Define in R a vector x
with the values 1,2,3 . Then sum up its values.
<- c(1, 2, 3)
x sum(x)
[1] 6
7 Vector wise computation
Square each value in the vector x
.
^2 x
[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.
<- c(1, 2, 3)
x
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.
<- c(1, 2, NA)
y 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.