vendredi 24 août 2018

Nested Ifelse statement in same table

I have a dataset below:

Col1     Col2    Spend
   A        0      100
   A        0      100
   B        0      100
   C        0      100
   D        0      200

I want to write an ifelse statement stating, if the sum of Col2 is greater than 0, then set Col2 = Spend. If the sum of Col2 is not greater than 0, then only apply the Spend Column to the corresponding rows where the value does not equal A and leave the rest as Col2 original values.

I want my final output to look like this:

Col1     Col2    Spend
   A        0      100
   A        0      100
   B      100      100
   C      100      100
   D      200      200

I think it would be something like this:

df$Col2 <- ifelse(sum(df$Col2)>0, df$Spend, ifelse(df$Col1!="A", df$Spend, df$Col2))

My issue is that when I run this, I check the sum again for Col2 and it still doesn't change. Not sure what I am doing wrong here.

Aucun commentaire:

Enregistrer un commentaire