Suppose I have 2 columns in a table
Quantity int Price decimal
And I want to calculate the value of a 3rd column called Total.
In SQL Server\'s transact-sql
In R this kind of operation is vectorized, meaning that you can create the column total
just by multiplying the other columns:
mytable$total <- mytable$quantity * mytable$price
or a little cleaner:
mytable$total <- with(mytable, quantity * price)
The "tidyverse" way uses dplyr::mutate
:
library(dplyr)
mytable <- mytable %>%
mutate(total = quantity * price)
If you want a function:
calcTotal <- function(x, y) {
x * y
}
And then you can use e.g.
mytable <- mytable %>%
mutate(total = calcTotal(quantity, price))
However, be aware that not all functions work "row-wise" in this way, in which case you might use the mapping functions from the purrr
package. For simple operations, it's probably not worth writing the function.