# Define example vector x
x <- 1:10
# Define rng
rng <- range(x, na.rm = TRUE)
# Rewrite this snippet to refer to the elements of rng
(x - rng[1]) /
(rng[2] - rng[1])
# Define example vector x
x <- 1:10
# Use the function template to create the rescale01 function
rescale01 <- function(x) {
# bdy
rng<-range(x,na.rm=T)
(x - rng[1]) / (rng[2] - rng[1])
}
# Test your function, call rescale01 using the vector x as the argument
rescale01(x)
# Define example vectors x and y
x <- c( 1, 2, NA, 3, NA)
y <- c(NA, 3, NA, 3, 4)
# Turn this snippet into a function: both_na()
both_na<-function(x,y){
sum(is.na(x) & is.na(y))
}
mean_ci <- function(level, x) {
se <- sd(x) / sqrt(length(x))
alpha <- 1 - level
mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2))
}
# Alter the mean_ci function
mean_ci <- function(x, level = 0.95) {
if (length(x) == 0) {
warning("`x` was empty", call. = FALSE)
return(c(-Inf, Inf))
}
se <- sd(x) / sqrt(length(x))
alpha <- 1 - level
mean(x) + se * qnorm(c(alpha / 2, 1 - alpha / 2))
}
replace_missings <- function(x, replacement) {
is_miss <- is.na(x)
x[is_miss] <- replacement
# Rewrite to use message()
message(sum(is_miss),replacement)
x
}
# Check your new function by running on df$z
replace_missings(df$z,0)
# Define col_sd() function
col_sd<-function(df){
output<-numeric(length(df))
for(i in seq_along(df)){
output[i]<-sd(df[[i]])
}
output
}
All the map functions inpurrrtake a vector,.x, as the first argument, then return.fapplied to each element of.x. The type of object that is returned is determined by function suffix (the part after_):
map()returns a list or data frame
map_lgl()returns a logical vector
map_int()returns a integer vector
map_dbl()returns a double vector
map_chr()returns a character vector
# Find the mean of each column
map_dbl(planes, mean)
# Find the mean of each column, excluding missing values
map_dbl(planes, mean, na.rm = TRUE)
# Find the 5th percentile of each column, excluding missing values
map_dbl(planes, quantile, probs = c(0.05), na.rm = TRUE)
# Save the result from the previous exercise to the variable models
models<-map(cyl, ~ lm(mpg ~ wt, data = .))
# Use map and coef to get the coefficients for each model: coefs
coefs<-map(models,~coef(.))
# Use string shortcut to extract the wt coefficient
map(coefs,"wt")
purrralso includes a pipe operator: %>%. The pipe operator is another shortcut that saves typing, but also increases readability. The explanation of the pipe operator is quite simple: x %>% f(y) is another way of writing f(x, y).
# Define models (don't change)
models <- mtcars %>%
split(mtcars$cyl) %>%
map(~ lm(mpg ~ wt, data = .))
# Rewrite to be a single command using pipes
models %>%
map(summary) %>%
map_dbl("r.squared")