Home > Net >  How to multiply with %<>% (from magrittr package) in R?
How to multiply with %<>% (from magrittr package) in R?

Time:01-31

Let's assign value to a variable:

thisIsANumberVariable <- 3
library(magrittr)
thisIsANumberVariable %<>%  5 #adds 5 to thisIsANumberVariable
thisIsANumberVariable
[1] 8
thisIsANumberVariable %<>% *6 # Should multiply thisIsANumberVariable by 8, but instead:
Error: unexpected '*' in "thisIsANumberVariable %<>% *"

Is there a way to multiply and assign simultaneously with %<>%?

CodePudding user response:

One option would be to use `*`() or the multiply_by alias (see e.g. ?magrittr::multiply_by for a list of available aliases):

thisIsANumberVariable <- 3

library(magrittr)

thisIsANumberVariable %<>%  5

thisIsANumberVariable
#> [1] 8

thisIsANumberVariable %<>% `*`(5)

thisIsANumberVariable
#> [1] 40

thisIsANumberVariable %<>% multiply_by(5)

thisIsANumberVariable
#> [1] 200

CodePudding user response:

The magrittr package provides a variety of aliases to use in place of symbols such as add, multiply_by, etc. See the Alias section in the vignette which is obtained via the R code vignette("magrittr") and to see them all try entering this:

help("extract", package = "magrittr")

For example, we can write

library(magrittr)

x <- 3
x %<>% multiply_by(5)
x
## [1] 15
  • Related