jeudi 3 septembre 2020

Use mutate and if else function in loop with vectors as index

I am attempting to a use a character vector as an index in a loop that runs through several mutate and if esle conditions. The code I am posting below is a simplified version of code I working through and I am using var <- "pr_cnt" instead of a character vector. The issue I am having is getting mutate to recognize the column name. The code runs in its current form but produces incorrect values of NA. Any help is greatly appreciated.

# 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)
}

Aucun commentaire:

Enregistrer un commentaire