0

In an answer to an R question on Stackoverflow on how to change the type of a column in a tribble I ran across the following code:

mtcars %<>% mutate(as.integer,qsec)
mtcars %<>% mutate(as.integer,[[6]])

What does the operator %<>% do? What package do I need to load to use it?

I have googled it but did not find it?

Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • 1
    Type in `?functionname` in your R console and typically you get some help documentation for the function. In this case, [`?%<>%`](https://magrittr.tidyverse.org/reference/compound.html). – r2evans Aug 31 '21 at 18:27
  • That the answer you found really not mention the package required? Can you provide a link so the answer can be improved? – MrFlick Aug 31 '21 at 18:28
  • 1
    @r2evans You need `?"%<>%"` in this case because of the special character. Or `help("%<>%")` – MrFlick Aug 31 '21 at 18:29
  • 1
    Right ... emacs/ess doesn't require that, both Rterm and RStudio do. Thanks. – r2evans Aug 31 '21 at 18:32

1 Answers1

3

It is from magrittr. It is called as assignment operator which does update the original object without doing. It's functionality is similar to the data.table := (though this may less efficient compared to data.table as data.table uses pass by reference assignment)

mtcars <- mtcars %>% 
     mutate(qsec = as.integer(qsec))

i.e. the %>% doesn't update the original object. It just prints the output to the console

mtcars %>% 
     mutate(qsec = as.integer(qsec))

The class of qsec remains the same

class(mtcars$qsec)
[1] "numeric"

But, if we do the %<>%, we don't need to update with <-

mtcars %<>% 
     mutate(qsec = as.integer(qsec))
class(mtcars$qsec)
[1] "integer"
akrun
  • 874,273
  • 37
  • 540
  • 662