【问题标题】:Define lapply function定义 lapply 函数
【发布时间】:2019-09-14 13:37:12
【问题描述】:

我有一个名为 df 的选项卡,其中包含几个分类器的结果:准确度、Npv、Ppv 等。

我想在数据框中添加一个名为“Points”的新列,其中包含此加权计算:

Points = Accuracy* 0,20 + Specificity *0,10 + Sensitivity *0.35 + Neg Pre Value*0.10 + Pos Pred value*0.25)

我正在尝试以这种方式使用 lapply:

df$Points <- apply(df[,3:7],1,make.calc)

该函数将从第 3 列到第 7 列进行计算,并将结果存储在名为 Points 的新列中。

我也以这种方式定义了我的函数 make.calc:

make.calc <- function(x) {
t <- function(x) { 
df$Accuracy * 0.2 + df$Specificity * 0.1 + df$Sensitivity * 0.35 + df$Neg_Pred_Value * 0.1 + df$Pos_Pred_Value * 0.25 }
 t } 

但我得到的是一个名为 Points 的新列,其中包含一个带有上面定义的模型的字符串...不是我需要的计算!

谁能帮我理解我的代码有什么问题??

这是我的 df 的输出:

> dput(head(df))
structure(list(Model = structure(1:6, .Label = c("Decision Tree", 
"Naive Bayes", "Neural Networks", "Random Forest", "SVM Linear", 
"SVM Radial"), class = "factor"), `Data source` = c("Without_DownSampling", 
"Without_DownSampling", "Without_DownSampling", "Without_DownSampling", 
"Without_DownSampling", "Without_DownSampling"), Specificity = c("0.984", 
"0.490", "0.980", "0.998", "0.982", "0.980"), `Pos Pred Value` = c("0.937", 
"0.321", "0.917", "0.991", "0.924", "0.917"), Accuracy = c("0.980", 
"0.588", "0.969", "0.996", "0.966", "0.967"), Sensitivity = c("0.963", 
"0.991", "0.926", "0.991", "0.898", "0.917"), `Neg Pred Value` = c("0.991", 
"0.995", "0.982", "0.998", "0.975", "0.980")), .Names = c("Model", 
"Data source", "Specificity", "Pos Pred Value", "Accuracy", "Sensitivity", 
"Neg Pred Value"), row.names = c(NA, 6L), class = "data.frame")

【问题讨论】:

  • transform(df, Points = Accuracy * 0.20 + Specificity * 0.1 + Sensitivity * 0.35 + Neg_Pred_Value * 0.1 + Pos_Pred_Value * 0.25)
  • 这不是你在 R 中定义函数的方式。stackoverflow.com/questions/32255367/…
  • 感谢您的快速回答!!! fransform() 函数不起作用,因为弹出错误:Error in Accuracy * 0.2 : non-numeric argument to binary operator
  • 请在预期输出中添加reproducible example,以便其他人更容易帮助您。
  • transform(df, Points = Accuracy * 0.20 + Specificity * 0.1 + Sensitivity * 0.35 + Neg_Pred_Value * 0.1 + Pos_Pred_Value * 0.25) 这似乎适用于您的示例数据

标签: r lapply


【解决方案1】:

在您提供的示例中,几乎所有变量都被归类为字符串。不幸的是,您不能对字符串执行任何计算,因此您应该首先将它们全部转换为数值变量。

df <- data.frame(purrr::map_at(df, 3:7, as.numeric), stringsAsFactors = FALSE)

这是一种方法,但我相信还有其他更好的选择。您还需要修复变量名称,以便其中没有空格。请注意,Neg Pre Value 不是一个好名字 - 建议您调整为 Neg_Pre_Value 或类似名称。

那么你不需要一个函数来执行你想要的任务。

您可以像这样简单地定义新变量:

df$Points <- df$Accuracy * 0.2 + df$Specificity * 0.1 + df$Sensitivity * 0.35 + df$Neg_Pred_Value * 0.1 + df$Pos_Pred_Value * 0.25 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多