[Rd] pipes and setNames

Gabor Grothendieck ggrothend|eck @end|ng |rom gm@||@com
Sun Apr 17 14:21:56 CEST 2022

When trying to transform names in a pipeline one can do the following
where for this example we are making names upper case.

  BOD |> (\(x) setNames(x, toupper(names(x))))()

but that seems a bit ugly and verbose.

1. One possibility is to enhance setNames to allow a function as a
second argument.  In that case one could write:

  BOD |> setNames(toupper)

2. One can already do the following with the existing `with` but is
quite verbose:
  BOD |> list() |> setNames(".") |> with(setNames(., toupper(names(.))))
but could be made simpler with a utility function.

This utility function is not as good for setNames but would still
result in shorter code than the anonymous function in the example at
the top of this email and is more general so it would also apply in
other situations too.  Here R would define a function with. (note dot
at end) which would be defined and used as follows.

  with. <- function(data, expr, ...) {
    eval(substitute(expr), list(. = data), enclos = parent.frame())

  BOD |> with.(setNames(., toupper(names(.))))

with. is not as efficient as straight pipes but in many cases such as
this it does not really matter and one just wants to get it done
without the parenthesis laden anonymous function.

Having both of these two would be nice to make it easier to use R pipes.

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-devel mailing list