Named Map Builder

John Mount

2017-07-22

seplyr introduces an operator called “named map builder” that is written as “:=”. Named map builder is a very simple bit of code that performs a very simple task: it adds names to vectors or lists (making them work more like maps).

Here are some examples:

library("seplyr")
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
'a' := 5
## a 
## 5
c('a' := 5, 'b' := 6)
## a b 
## 5 6
c('a', 'b') := c(5, 6)
## a b 
## 5 6

The left-side argument of the := operator is called “the names”, and the right-side argument is called “the values”. The := operators returns the values with the names set to names.

A great use of the := operator is using it to conveniently build arguments lists for functions such as seplyr::mutate_se(). This works for simple explicit code such as the following.

datasets::iris %>%
  summarize_se("Mean_Sepal_Length" := "mean(Sepal.Length)")
##   Mean_Sepal_Length
## 1          5.843333

Slightly more complicated code such as:

datasets::iris %>%
  group_by_se("Species") %>%
  summarize_se(c("Mean_Sepal_Length" := "mean(Sepal.Length)",
                 "Mean_Sepal_Width" := "mean(Sepal.Width)"))
## # A tibble: 3 x 3
##      Species Mean_Sepal_Length Mean_Sepal_Width
##       <fctr>             <dbl>            <dbl>
## 1     setosa             5.006            3.428
## 2 versicolor             5.936            2.770
## 3  virginica             6.588            2.974

Or even parametric code such as:

resultColumn <- "summary_value"
datasets::iris %>%
  group_by_se("Species") %>%
  summarize_se(resultColumn := "mean(Sepal.Length)")
## # A tibble: 3 x 2
##      Species summary_value
##       <fctr>         <dbl>
## 1     setosa         5.006
## 2 versicolor         5.936
## 3  virginica         6.588

To see more please try:

help(`:=`, package = 'seplyr')
print(`:=`)