使用mutate和if else函数以向量作为索引循环运行

问题描述

我正在尝试将字符向量用作循环中的索引,该循环贯穿多个mutate和esle条件。我在下面发布的代码是我正在处理的代码的简化版本,并且我使用的是var <- "pr_cnt"而不是字符向量。我遇到的问题是无法识别列名。该代码以其当前形式运行,但会产生不正确的NA值。任何帮助将不胜感激。

# Create test data.frame
test <- data.frame(numfish = c(1:10),Hrsfished = runif(n = 10,min = 2,max = 8),pr_cnt = runif(n = 10,min = 12,max = 20),dfished = rep(12,times = 10),DF = c(41:50))
#Run simplified for loop using var <- "pr_cnt" in ifelse statement
for(i in 1:1){
  var <- "pr_cnt"
  m<- mutate(test,dummy = ifelse(Hrsfished < pr_cnt,.data[[var]]/2),0)
}

解决方法

我建议这种方法:

private val handler: CoroutineExceptionHandler = CoroutineExceptionHandler{ _,exception ->
    println("Exception thrown in one of the children: $exception")
}

输出:

library(dplyr)
#Code
# Create test data.frame
test <- data.frame(numfish = c(1:10),Hrsfished = runif(n = 10,min = 2,max = 8),pr_cnt = runif(n = 10,min = 12,max = 20),dfished = rep(12,times = 10),DF = c(41:50))
#Run simplified for loop using var <- "pr_cnt" in ifelse statement
for(i in 1:1){
  var <- "pr_cnt"
  m<- test %>% mutate(dummy = ifelse(Hrsfished < pr_cnt,.[[var]]/2,0))
}