Specify a vector with numeric elements 1 and 3 and a character element “c”.
What type will the resulting object be?
Check your intuition with R.
x <- c(1,3,"c")
typeof(x)
## [1] "character"
Create a named list containing a data frame, a character vector and a list. Access the first element of the first element and the second element.
# One solution:
z <- list(df = data.frame(x = c(2, 2), y = c("a", "b")),
g = "c",
f = list(1, 2)
)
z$df[1]
## x
## 1 2
## 2 2
z[[2]]
## [1] "c"
Assign the name “x” to an integer vector from 1 to 10.
Create a logical vector “z” whose elements store whether x is greater than 2 and less than 8.
Compute the number of times the above condition is true (use sum()
).
x <- c(1:10)
x
## [1] 1 2 3 4 5 6 7 8 9 10
z <- x > 2 & x < 8
z
## [1] FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE
sum(z)
## [1] 5
sum(x > 2 & x < 8)
## [1] 5
Given the data frame below, create a new column called “c” that contains the product of “a” and “b”. Do this using $
and [
indexing (and maybe names()
). Remember, data frames are (special) lists!
df <- data.frame(
a = c(1,1,2,3,4),
b = c(3,2,2,4,5)
)
Your solution:
df$c <- df$a * df$b
#Or
df["c"] <- df["b"] * df["a"]
In this task, you will learn a few important functions in base R.
Often, you want to create sequences of objects.
You can do so using the rep()
function:
x <- c(1,2,3)
rep(x, 3)
## [1] 1 2 3 1 2 3 1 2 3
rep(x, each = 3)
## [1] 1 1 1 2 2 2 3 3 3
Another way of creating sequences is seq()
:
seq(1, 5)
## [1] 1 2 3 4 5
1:5
## [1] 1 2 3 4 5
seq(1,5, by = 2)
## [1] 1 3 5
You should also know some basic string manipulations from the beginning.
With paste()
you can concatenate strings:
x <- "a"
paste(x, 3)
## [1] "a 3"
paste(3, x)
## [1] "3 a"
paste(3, x, sep = "")
## [1] "3a"
Can you spot the difference to paste0()
?
paste0(3, x)
## [1] "3a"
Some very basic (math) functions: sqrt()
, exp()
, log()
, abs()
, sum()
, max()
, min()
, length()
(length of an r object).
Create a character vector with 20 elements: “1st element”, “2nd element”, “3rd element”, “4th element”, etc.
chr <- paste0(1:20, c("st", "nd", "rd", rep("th", 17)))
chr <- paste(chr, "element")
chr
## [1] "1st element" "2nd element" "3rd element" "4th element" "5th element"
## [6] "6th element" "7th element" "8th element" "9th element" "10th element"
## [11] "11th element" "12th element" "13th element" "14th element" "15th element"
## [16] "16th element" "17th element" "18th element" "19th element" "20th element"
Write a function to compute the mean of a vector. Of course, without using the mean()
function.
Define a vector you want to test your function on and specify the expected result:
x <- c(1,2,3,4,5)
mean(x)
## [1] 3
Write the function and test it:
mean_fun <- function(x) {
sum(x) / length(x)
}
mean_fun(x)
## [1] 3