R Helper Functions to Increase Efficiency
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
At Inspire, we have built an internal R package consisting of all kinds of functions to achieve business functionalities. In this package, we created some helper functions to make some frequent jobs simpler. Some of the helper functions are based on solutions provided on public websites, such as StackOverflow. In this post, I would like to share some of the helper functions we use in daily work. Hope you can benefit or get inspired from them!
-
Calculate weights from a non-negative vector using
lw()
:We use this function a lot because we deal with a lot of redistribution jobs. The weight of each entry is calculated as its proportion to the sum of all entries. If the sum is equal to 0, then all weights should be equal across all entries because they should be all equal to 0. The source code is
lw <- function(v) { if (sum(v, na.rm = TRUE) == 0) { 1 / length(v) } else { v / sum(v, na.rm = TRUE) } }
An example is
> lw(c(1,2,3)) [1] 0.1666667 0.3333333 0.5000000