r-数据帧与标头应用传递行



我有一个dataframe df。我想将功能myfun应用于其每一行。但是理想情况下,我希望在函数myfun中使用数据框的标题名称。想知道这是否可以在myfun中明确重命名列的情况下完成。谢谢!

myfun() <- function(rowdf) {
    //statements
    if(rowdf$price > 1000){
        val = "high"
    } elseif(rowdf$num_floors > 3){
        val = "high"
    } else{
        val = "low"
    }
    return(val)
}
//df has columns price and num_floors
bld_vals = apply(df, 1, myfun)

有几件事要更改,

  1. 您可以在以这种方式传递的数据框架上使用" $"。
  2. 无需申请您的意图。

请按照以下代码:

myfun <- function(rowdf,price,num_floors) {
val <- ifelse (rowdf[,price]>1000,"high",ifelse(rowdf[,num_floors]>3,"high","low"))
return(val)
}

df$val <- myfun(df,"price","num_floors")

最新更新