It is not possible to directly connect arithmetic operators using the R pipe (|>). The pipe is used to connect functions and pass the output from one function as the input to the next function. Arithmetical operations are performed within a function or by using the usual arithmetic operators (+, -, *, /) in R.
To connect arithmetic operations with the pipe, first, we need to perform the operations inside a function such as mutate
or transmute
from the dplyr
package.
For example, suppose we have a data frame df
with columns x
and y
. To perform arithmetic operations on these columns using the pipe, we can use the mutate
function:
library(dplyr)
df %>%
mutate(z = x + y,
w = x - y,
q = x * y,
r = x / y)
In this example, the mutate
function is used to create new columns z
, w
, q
, and r
with the result of arithmetic operations on columns x
and y
.
Alternatively, we can use the usual arithmetic operators to perform operations and then pass the result to a function using the pipe. For example:
df %>%
transmute(z = x + y, w = x - y) %>%
summarize(sum_z = sum(z), sum_w = sum(w))
In this example, the transmute
function is used to create new columns z
and w
with the result of arithmetic operations on columns x
and y
. The summarize
function is then used to calculate the sum of these columns.
Asked: 2021-10-08 11:00:00 +0000
Seen: 8 times
Last updated: Sep 30 '21