samedi 25 avril 2020

ifelse add a calculated field in R dataframe

Hi everyone I am trying to add a calculated field into a data frame in R using several conditionals at the same time.

I have the following data frame called df

     ID A                 AA          AAA        AAAA   AAAAA
1     1 a                 no            57         10     100.0%
2     2 b                 no            32          7      70.0%
3     3 c                yes            30          7      70.0%
4     4 d                 no            52          7      70.0%

And I want to add a new field called Z with the following conditions that basically add 25% in case is true

ifelse(df$AA=="yes",0.25,0) + ifelse(df$AAA<30,0.25,0) + ifelse(df$AAAA>4,0.25,0)

So I added the following code

df$Z<-as.data.frame(ifelse(df$AA=="yes",0.25,0)+ifelse(df$AAA<30,0.25,0)+ifelse(df$AAAA>4,0.25,0))

but I got the following error

Error in `$<-.data.frame`(`*tmp*`, Z, value = list(`ifelse(df$AA=="yes",0.25,0)+ifelse(df$AAA<30,0.25,0)+ifelse(df$AAAA>4,0.25,0)` = numeric(0))) : 
  replacement has 0 rows, data has 200

I guess I am trying to translate an excel formula into R which is

=IF(C2="yes";25%;0)+IF(D2<30;25%;0)IF(E2>4;25%;0)

Best Regards

Aucun commentaire:

Enregistrer un commentaire