vendredi 23 avril 2021

How to apply unique functions to multiple rows of the dataset using if statement in R?

In this data set (df), I want to apply a different equation based on species to calculate a new output stored in "Std.Val1"

Year Site Quadrant species Val1 Val2 Std.Val1
2019   1     1        A    20    30     NA
2019   1     1        B    NA    25     NA
2019   1     2        C    20    10     NA
2019   1     2        D    11    22     NA

c_A <- 1
m_A <- 2

c_B <- 2
m_B <- 5

c_C <- 10
m_C <- 12

c_D <- 11
m_D <- 2

I tried following this example to write my code

df %>%
    mutate(
      Std.Val1 = ifelse(species == "A" ~ ((log(Val1) - c_A )/(m_A)),
                 ifelse(species == "B" ~ ((log(Val1) - c_B )/(m_B)),
                 ifelse(species == "C" ~ ((log(Val1) - c_C )/(m_C)),
                 ifelse(species == "D" ~ ((log(Val1) - c_D )/(m_D)), NA))))
              )

but I keep running into an error that reads: "Error: Problem with mutate() input Std.Val1. x 'language' object cannot be coerced to type 'logical' ℹ Input nem1 is ifelse(...)"

Aucun commentaire:

Enregistrer un commentaire