如何将条件函数应用于数据帧的每一行

问题描述 投票:0回答:0

我有一个如下所示的数据框:

x <- c(1,2,3,4)
coef_ind <- c(0.5,0.6,1,2)
type <- c("power","power","expo","expo")
tf <- data.frame(x=x,coef_ind=coef_ind,type=type)

> tf
  x coef_ind  type
1 1      0.5 power
2 2      0.6 power
3 3      1.0  expo
4 4      2.0  expo

我写了一个如下所示的函数:

cal <- function(df){
  
  x = df['x']
  type = df['type']
  coef = df['coef_ind']
  
  if(type == "power"){
    outcome = x^coef
  }
  
  if(type == "expo"){
    outcome = 1- exp(- coef*x)
  }
  return(outcome)
}

现在,我想将该函数应用于每个表行。因此:

apply(tf,1,cal)

但是,我收到错误提示

Error in x^coef : non-numeric argument to binary operator
enter code here

您能分享一下您对这个问题的了解吗?非常感谢。

r apply
© www.soinside.com 2019 - 2024. All rights reserved.