繁体   English   中英

如何在 r 中编写用户定义的函数?

[英]How do I write a user defined function in r?

假设我在表中有 2 列

数量 int 价格 十进制

我想计算名为 Total 的第三列的值。

在 SQL Server 的 transact-sql 中,我可以简单地写

select Price*Quantity as Total from mytable

或者我可以写一个使用过的定义函数 CalcTotal 然后写

select calcTotal(quantity,price) as total from mytable

如何在 R 中编写函数以向数据帧添加类似的列?

我试图在这里提出我的问题

在 R 中,这种操作是向量化的,这意味着您可以通过乘以其他列来创建列total

mytable$total <- mytable$quantity * mytable$price

或者更清洁一点:

mytable$total <- with(mytable, quantity * price)

“tidyverse”方式使用dplyr::mutate

library(dplyr)
mytable <- mytable %>%
    mutate(total = quantity * price)

如果你想要一个函数:

calcTotal <- function(x, y) {
  x * y
}

然后你可以使用例如

mytable <- mytable %>%
  mutate(total = calcTotal(quantity, price))

但是,请注意并非所有函数都以这种方式“按行”工作,在这种情况下,您可以使用purrr包中的映射函数。 对于简单的操作,可能不值得编写函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM