What is the %<-% operator in R?

Viewed 121

I came across a new piped R operator %<-% on this blog: https://blogs.rstudio.com/ai/posts/2019-09-30-bert-r/ in the tokenize_fun() function.

What is this operator called? What does it do?

I could not find any information about it on google. I am aware of other pipe operators like %>%, %T>%, %$%

2 Answers

It is a multiple assignment operator from zeallot

%<-% and %->% invisibly returnvalue.

These operators are used primarily for their assignment side-effect. %<-% and %->% assign into the environment in which they are evaluated.

i.e. it creates multiple objects from a single line of code

> library(zeallot)
> c(x, y, z) %<-% c(1, 3, 5)
> x
[1] 1
> y
[1] 3
> z
[1] 5

If one looks at the code in the linked post, it is evident what this operator does. Let's take a look at the first line in the tokenize_fun:

tokenize_fun = function(dataset) {
  c(indices, target, segments) %<-% list(list(),list(),list())

That line essentially creates three empty lists in a main list to hold indices, target, and segments. These are later populated via append.

Edit: There's an answer on the specific name of the function below. I'll leave this answer here in case it may provide some additional context.

In general, one can define an infix operator in the %. %` form. In this case, the authors perhaps wanted to "mimic" something like python's multiple assignment via a one-liner.

Related