mercredi 29 avril 2020

How do I form conditional statements (if) a value of a variable > another variable's, then conduct an equation using those variables? On R

I'm a beginner to R. I'm using an Excel dataset (which I've already imported onto my Rstudio).

I have two main variables, which are the hit rate and false alarm rates from an n-back task. I've already put them as numerical variables on my imported Excel sheet exactly as one_back_hit_rate and one_back_fa_rate.

I need to figure out

  1. if one_back_hit_rate > one_back_fa_rate , then I'd apply this equation: 0.5 + ((one_back_hit_rate - one_back_fa_rate) * (1 + one_back_hit_rate - one_back_fa_rate))/(4 * one_back_hit_rate * (1 - one_back_fa_rate)) to create a new variable called one_back_aprime.
  2. But if one_back_hit_rate < one_back_fa_rate , then I'd apply this different equation: 0.5 + ((one_back_fa_rate - one_back_hit_rate) * (1 + one_back_fa_rate - one_back_hit_rate))/(4 * one_back_fa_rate * (1 - one_back_hit_rate)) to create the same new variable called one_back_aprime.
  3. And if one_back_hit_rate = one_back_fa_rate , then one_back_aprime = 0

So far the code that I have tried out but isn't working:

nback_mornings_data <- read_excel("New_nback_R_2.xlsx", sheet = 1)
df <- data.frame(nback_mornings_data)

df[,-1] <- round(df[,-1],2)

if(one_back_hit_rate > one_back_fa_rate) {
  df$one_back_aprime <- 0.5 + ((one_back_hit_rate - one_back_fa_rate) * (1 + one_back_hit_rate - one_back_fa_rate))/(4 * one_back_hit_rate * (1 - one_back_fa_rate))
  } else if (one_back_hit_rate < one_back_fa_rate) { 
    df$one_back_aprime <- 0.5 + ((one_back_fa_rate - one_back_hit_rate) * (1 + one_back_fa_rate - one_back_hit_rate))/(4 * one_back_fa_rate * (1 - one_back_hit_rate))
  } else if (one_back_hit_rate == one_back_fa_rate) {
    df$one_back_aprime <- 0.5
  }

Everything up to the if statements runs fine. I'm very sure I'm missing something crucial at the beginning (I'm a beginner again! Just trying to learn) I would REALLY appreciate some help on this!

Note: When I run the code, this error message comes up: Error in if (one_back_hit_rate > one_back_fa_rate) { : missing value where TRUE/FALSE needed I don't have any NA values in my entire dataset, and I'm not using a for loop, therefore I'm not sure how to get around this error. If you have any suggestions on this, I'd really appreciate it!

Aucun commentaire:

Enregistrer un commentaire