Writing functions for use in dplyr::mutate() can be done using the following steps:
- Use a function that returns a single value:
return_single_value <- function(x){
sum(x)
}
iris %>% mutate(
result = return_single_value(Petal.Length)
)
- Use a function that returns the same number of values as given:
return_length_values <- function(x){
paste0("result_", 1:length(x))
}
iris %>% mutate(
result = return_length_values(Petal.Length)
)
- Use a function that returns neither a single value nor the same number of values as given:
return_three_values <- function(x){
c("A", "b", "C")
}
iris %>% mutate(
result = return_three_values(Petal.Length)
)
- Force repetition of the function to fit the length of the vector:
rep_until <- function(x){
rep(c("A", "b", "C"), length.out = length(x))
}
iris %>% mutate(
result = rep_until(Petal.Length)
)