jgaeb
jgaeb

Reputation: 317

Is it possible to dynamically assign variable names to a vector in a magrittr pipeline?

Certain functions in R, such as quantile, lose vector names that I would like to keep. Let's say I set up the following pipeline:

> dist <- c(0, 1, 2, 3)
> qnts <- c(lower = 0.25, upper = 0.75)
> qnts %>% quantile(dist, .)
#  25%. 75%
# 0.75 2.25
> qnts %>% quantile(dist, ., names = FALSE)
# [1] 0.75 2.25

In both cases, quantile loses the names from the qnts vector.

Unsurprisingly, assignment within the pipeline doesn't work:

> qnts %>% quantile(dist, .) %>% names(.) <- c("upper", "lower")
# Error in qnts %>% quantile(dist, ., names = FALSE) %>% naes(.) <- c("upper",  :
#  could not find function "%>%<-"

I also can't use assign---because names(.) is not a variable---or rename---in this particular instance, I could use rename(., c("25%" = "lower", "75%" = "upper")), but in my use case, the quantiles change dynamically.

There must be some way to intelligently recover the names of qnts, but I can't figure it out.

Upvotes: 1

Views: 302

Answers (2)

akrun
akrun

Reputation: 887951

With magrittr, set_names would be more appropriate (which is an Alias for `names<-`)

library(magrittr)
qnts %>%
   quantile(dist, .) %>% 
   set_names(c("upper", "lower"))
#  upper lower 
# 0.75  2.25 

Or can change the last step with setNames from base R instead of set_names

Another option would be to use names<-, but it would be less easier to understand

qnts %>%
   quantile(dist, .) %>%
   `names<-`(c("upper", "lower"))

Upvotes: 4

jgaeb
jgaeb

Reputation: 317

Wrapping the assignment in braces and using a tee pipe seems to work:

qnts %>% quantile(dist, .) %T>% {names(.) <- c("upper", "lower")}

Upvotes: 1

Related Questions