# Create a new function to multiply two vectors togethermultiply_columns <-function(x,y){return(x*y)}multiply_columns(x = city$porto, y = city$aberdeen) %>%head(5)
multiply_columns(x = city$nairobi, y = city$aberdeen) %>%head(5)
[1] NA NA NA NA NA
Use it in Mutate
city %>%mutate(por_aber =multiply_columns(x = porto, y = aberdeen),nai_aber =multiply_columns(x = nairobi, y = aberdeen))
# A tibble: 100 × 6
porto aberdeen nairobi genoa por_aber nai_aber
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 -0.898 0.275 NA 0.100 -0.247 NA
2 -0.641 0.194 NA -1.67 -0.124 NA
3 1.01 -0.772 NA -0.170 -0.779 NA
4 0.319 1.62 NA 0.639 0.515 NA
5 -0.692 0.679 NA 0.196 -0.470 NA
6 0.239 0.549 NA 0.620 0.131 NA
7 0.0206 -0.852 NA -1.18 -0.0175 NA
8 -1.40 -0.660 NA -1.23 0.924 NA
9 1.20 0.0311 NA 0.477 0.0375 NA
10 1.27 0.544 NA 0.0947 0.691 NA
# ℹ 90 more rows
Edge Cases are important
Producing Errors and Warnings are good practise.
Test for things that might produce unexpected results.
divide_columns <-function(x, y) {if(any(y==0)){warning("Division by 0 is likely. You should expect to see a NAN")} temp_var <- x / yif (any(is.na(temp_var))) {warning("The function has a produced NA")return(temp_var) } else {return(temp_var) }}divide_columns(x = city$nairobi, y = city$aberdeen) %>%head(5)
Warning in divide_columns(x = city$nairobi, y = city$aberdeen): The function
has a produced NA
[1] NA NA NA NA NA
divide_columns(x =rep(0,100), y = city$aberdeen) %>%head(5)