How to do it...

Writing functions for use in dplyr::mutate() can be done using the following steps:

  1. Use a function that returns a single value:
return_single_value <- function(x){
sum(x)
}
iris %>% mutate(
result = return_single_value(Petal.Length)
)
  1. 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)
)
  1. 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)
)
  1. 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)
)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.203.215