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 %<>%?
One option would be to use `*`()
or the multiply_by
alias (see eg ?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
The magrittr package provides a variety of aliases to use in place of symbols. These include add
, multiply_by
and others. See the Alias section in the vi.nette which is obtained via the R code vi.nette("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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.