【发布时间】:2016-12-26 21:17:02
【问题描述】:
到目前为止,我已经看到应用带有两个参数的函数并使用列索引号。有没有比使用参数更好的方法但应用整个列名? 我有一个包含多列的表,并且使用了每个列的值。
我的实际df比这个大,功能也更复杂。所以我希望传递整个 df 名称而不是这样 apply(df,c['price','quantity','level'],MARGIN=1, FUN= myfunc)
df= data.frame(price = c(204, 45, 62),
type = c("F", "F","M"),
quantity = c(400,33,2),
level = c(1,3,1)
)
我正在寻找我这样做的东西:
myfun = function(){
//uses every data row in the dataframe; without rewriting df all the time
if (df$type == "F")
return (df$price*df$quantity*df$level)
}
apply(df, FUN = myfunc)
【问题讨论】:
-
Reduce(`*`, df[df$type == "F", -2])也许 -
或
library(dplyr)这可能有效:df %>% filter(type == "F") %>% transmutate(return_value = price*quantity*level)
标签: r