0

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 I could simply write

select Price*Quantity as Total from mytable

or I could write a used defined function CalcTotal and then write

select calcTotal(quantity,price) as total from mytable

How do I write a function in R to add a similar column to a dataframe?

I tried to formulate my question here

Kirsten
  • 15,730
  • 41
  • 179
  • 318

1 Answers1

0

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.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Thank you. I asked a question that I think is related to your last paragraph. https://stackoverflow.com/questions/64745336/how-do-i-write-a-function-in-r-to-do-cacluations-on-a-record – Kirsten Nov 09 '20 at 03:03