How do I write a user defined function in r?

前端 未结 1 1170
孤城傲影
孤城傲影 2021-01-28 23:23

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

相关标签:
1条回答
  • 2021-01-28 23:33

    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.

    0 讨论(0)
提交回复
热议问题