jeudi 30 juillet 2020

Mutating a variable depending on year using r

I am trying to standardized a variable by a national average depending on the year to create a new variable that is a Z score. Here is an example dataset:

 DF:
 Var1   Var2
 240     2015
 210     2018
 206     2016
 248     2017
 235     2019
----etc

I am using the following code:

DF$NewZScore<- if (DF$Var2== "2015"){
  (DF$Var1 - 229)/20
} else if (DF$Var2== "2016"){
  ((DF$Var1 - 228)/21
  } else if (DF$Var2== "2017"){
  ((DF$Var1 - 229)/20
    } else if (DF$Var2== "2018"){
  ((DF$Var1 - 230)/19
  } else if (DF$Var2== "2019"){
  ((DF$Var1 - 231)/19
} else {
  + 1000
}

The years 2015 through 2019 are the years I am wanting, there are a few other years which I will filter out after (thus, the + 1000). This code is mutating Var1 by the 2015 criteria rather than mutating the variable by the year in Var2. Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire