【问题标题】:R error: Error in x[[jj]] <- v : attempt to select less than one element in integerOneIndex when running functionR 错误:x[[jj]] <- v 中的错误:运行函数时尝试在 integerOneIndex 中选择少于一个元素
【发布时间】:2024-05-03 08:40:02
【问题描述】:

当我尝试在我的测试数据集上运行以下函数代码 sn-p 时,我看到了上述错误:

df <- data.frame(id=c(1,2,3,4), actual=c(0,1,0,1), score=c(.7223,.8904,.0037,.0025), prediction=c(1,0,0,1),
                 black=c(.6476,.0534,.0702,NA), hispanic=c(.1406,.8262,.0645,NA), asian=c(.1100,.0141,.7930,NA),
                 white=c(.0444,.0740,.0056,NA), female=c(0,1,0,1), male=c(1,0,1,0), weight=c(.1755,.8101,.1332,.6420))

adverse_impact_ratio <- function (
  data_frame,
  lower_outcome_favorable,
  outcome,
  true_outcome,
  pg_names,
  cg_names,
  sample_weight,
  air_threshold
) {

  data <- data_frame
  
  if (is.null(sample_weight)) {
    data['sample_weight'] <- 1
    sample_weight <- 'sample_weight'
  }
  
  if (lower_outcome_favorable) {
    data[outcome] <- 1 - data[outcome]
    if (!is.null(true_outcome)) {
      data[true_outcome] <- 1 - data[true_outcome]
    }
  }
}

adverse_impact_ratio(
  df, 
  1, 
  df$score, 
  df$actual, 
  pg_names=c('black', 'hispanic', 'asian', 'female'), 
  cg_names=c('white', 'white', 'white', 'male'), 
  df$weight, 
  0.9) 

任何想法我做错了什么?我在这个论坛上看到过类似的问题,但它们通常涉及 for 循环,这里不是这种情况。谢谢!

【问题讨论】:

    标签: r function


    【解决方案1】:

    尝试:

    adverse_impact_ratio(
      df, 
      1, 
      "score", 
      "actual", 
      pg_names=c('black', 'hispanic', 'asian', 'female'), 
      cg_names=c('white', 'white', 'white', 'male'), 
      df$weight, 
      0.9) 
    

    【讨论】:

    • 谢谢!我永远不会猜到问题是缺少引号!
    • 还在最后一个函数括号前添加“return(data)”
    最近更新 更多