- 1
-
We need to load the
tidyversepackage (orpurrr). - 2
- Write a function to calculate the square.
- 3
- Define a vector of numbers.
- 4
-
Use
mapto apply the function to the vector. - 5
-
Use a temporary function (
\(x) x^2) to calculate the square of each number.
Practical 1
Introducing purrr and map
- Write a function that calculates the square of a number (i.e., \(x^2\)).
- Create a vector
xcontaining the numbers1to10. - Use
map()to apply your function to each number in the vector. - Repeat, but this time use a temporary function.
- Modify your previous answer so that the result is returned as a numeric vector instead of a list.
- Write a vector of names (e.g.,
c("Alice", "Bob")). - Use
map_chr()to convert this vector into greetings (e.g., “Hello, Alice!”).
- Given the below list of numeric vectors, use
map_dbl()to compute the mean of each vector.
numbers <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))- Use the code below to generate 10 datasets and save them into a subfolder of your current working directory.
- 1
- Create a matrix from a vector of 500 random numbers and convert it to a data frame.
- 2
-
Set the names of the data frame to
var1,var2, etc. - 3
- Create a new folder “datasets”
- 4
- For each letter from A to J
- 5
- Generate a dataset and save it as a CSV file
Use
mapto import all CSV files into this folder as a list of data frames.Use
list_rbindto convert the list into a single data frame. Use thenames_toargument to retain the dataset names.