假设我在一个表中有2列
数量int 价格十进制
我想计算名为Total的第三列的值。
在SQL Server的transact-sql中,我可以简单地编写
select Price*Quantity as Total from mytable
或者我可以编写一个使用的定义函数CalcTotal然后编写
select calcTotal(quantity,price) as total from mytable
如何在R中编写一个函数以向数据框添加类似的列?
我试图提出问题here
答案 0 :(得分:0)
在R中,这种操作是 vectorized ,这意味着您可以通过乘以其他列来创建列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
包中的映射函数。对于简单的操作,可能不值得编写该函数。