Home > Back-end >  Make a column by two columns and conditions of the third column
Make a column by two columns and conditions of the third column

Time:03-08

I have a dataset like this:

structure(list(INDEX1 = c(60L, 83L, 10L, 11L, 11L, 54L, 27L), 
    status = c("Y", "N", "Y", "Y", "N", "N", "Y"), index2 = c(12L, 
    11L, 12L, 14L, 17L, 11L, 8L)), class = "data.frame", row.names = c(NA, 
-7L))
 INDEX1 status  index2
 60   Y         12
 83   N         11
 10   Y         12
 11   Y         14
 11   N         17
 54   N         11
 27   Y         8

I want to make a column (index3) that keep values of index1 if status =="Y" and add the values of index2 if status=="N".

CodePudding user response:

We may use ifelse/case_when

library(dplyr)
df1 %>% 
   mutate(index3 = case_when(status == "Y" ~ INDEX1, TRUE ~ index2))

CodePudding user response:

We can use fcase with data.table:

library(data.table)

setDT(dt)[, index3 := fcase(status == "Y", INDEX1, status == "N", index2)]

Output

   INDEX1 status index2 index3
1:     60      Y     12     60
2:     83      N     11     11
3:     10      Y     12     10
4:     11      Y     14     11
5:     11      N     17     17
6:     54      N     11     11
7:     27      Y      8     27

CodePudding user response:

From your statement:

... keep values of index1 if status =="Y" and add the values of index2 if status=="N"

I infer INDEX1 if "Y", and INDEX1 index2 if "N". From that, base R options:

with(zz, INDEX1   index2*(status == "N"))
# [1] 60 94 10 11 28 65 27

## alternatively
with(zz, INDEX1   ifelse(status == "N", index2, 0))

CodePudding user response:

In base R we can use ifelse like below

> transform(df, index3 = ifelse(status == "Y", INDEX1, index2))
  INDEX1 status index2 index3
1     60      Y     12     60
2     83      N     11     11
3     10      Y     12     10
4     11      Y     14     11
5     11      N     17     17
6     54      N     11     11
7     27      Y      8     27
  • Related