简体   繁体   中英

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

In the last column, if you have '%' sign then remove it before doing comparison.

df$AAAAA <- as.numeric(sub('%', '', df$AAAAA))
df$Z <- with(df, ifelse(AA=="yes",0.25,0) + ifelse(AAA<30,0.25,0) +
                 ifelse(AAAA>4,0.25,0))

You can also do this without ifelse

df$Z <- with(df, (AA == 'yes') * 0.25 + (AAA < 30) * 0.25 + (AAAA > 4) * 0.25)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM