通过两列和第三列的条件制作一列

Make a column by two columns and conditions of the third column

我有这样的数据集:

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

我想创建一个列 (index3),如果 status =="Y" 则保留 index1 的值,如果 status=="N" 则添加 index2 的值。

我们可以使用ifelse/case_when

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

我们可以使用 fcasedata.table:

library(data.table)

setDT(dt)[, index3 := fcase(status == "Y", INDEX1, status == "N", 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

根据您的陈述:

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

我推断 INDEX1 如果是“Y”,INDEX1+index2 如果是“N”。由此,基本 R 选项:

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

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

在 base R 中我们可以像下面这样使用 ifelse

> 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