mardi 12 janvier 2021

running if and else within a for loop across columns

I am attempting to have R read across columns by row and evaluate whether values from two adjacent cells are equal. If the values are equal, I want R to count this occurence in a new variable. Here is example data (df):

Var1 Var2 Var3
2 3 3
3 3 3
1 2 3
3 2 1

...and I want to get here:

Var1 Var2 Var3 NewVar
2 3 3 1
3 3 3 2
1 2 3 0
3 2 1 0

One example set of code I have tried out is the following:

df$NewVar <- 0

for (i in 1:2){
  if (df[i]==df[i+1]){
    df$NewVar <- df$NewVar + 1
  }
  else{
    df$NewVar <- df$NewVar
  }
}

This particular set of code just returns 0s in the NewVar variable.

Any sort of help would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire