[Rd] pipes and setNames

Hadley Wickham h@w|ckh@m @end|ng |rom gm@||@com
Tue Apr 19 14:01:45 CEST 2022


On Tue, Apr 19, 2022 at 1:56 AM Jan Netík <netikja using gmail.com> wrote:
>
> I agree that would be nice, but this task is indeed manageable with
> one-line function definition as mentioned above.
>
> For reference, take a look at dplyr::rename_with which does something
> nearly identical as your proposal does. Note that even tidyverse setNames
> implementation does not allow for functions nor lambdas.

The closest equivalent to setNames() is rlang::set_names() which does
allow you to supply a character vector, a function, or NULL:

``` r
library(rlang)

x <- c(a = 1, b = 2, c = 3)
x |> set_names(c("x", "y", "z"))
#> x y z
#> 1 2 3
x |> set_names(toupper)
#> A B C
#> 1 2 3
x |> set_names(NULL)
#> [1] 1 2 3
```

When called with only one argument it uses the vector values for the names:

``` r
x |> set_names()
#> 1 2 3
#> 1 2 3
```

(this is often useful before lapply() and friends, if the vector is,
e.g. a vector of paths)

It also supports ... so you can avoid `c()` for simple cases:

```r
x |> set_names("x", "y", "z")
#> x y z
#> 1 2 3
```

And is a little stricter when it comes to the length of supplied names:

``` r
x |> set_names("x", "y")
#> Error in `set_names()`:
#> ! The size of `nm` (2) must be compatible with the size of `x` (3).
x |> setNames(c("x", "y"))
#>    x    y <NA>
#>    1    2    3
```

Hadley

-- 
http://hadley.nz



More information about the R-devel mailing list