【问题标题】:Apply function using multiple values in rows在行中使用多个值应用函数
【发布时间】: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


【解决方案1】:

你可以这样做:

res = apply(df, 1, function(t){
    if(t["type"] == "F") 
        return(as.numeric(t["price"]) * as.numeric(t["quantity"]) * as.numeric(t["level"]))
    else
        return("NO")
})

我希望这可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2013-07-15
    相关资源
    最近更新 更多