使用ifelse添加基于其他列的新列和标签

时间:2018-11-12 13:03:18

标签: r if-statement

我有一个数据集,我想使用ifelse创建新列,请参见下文。

DB  DL NEW
  NO  NO  NO
  NO  NO  NO
  NO YES  DL
  NO YES  DL
  YES  NO  DB
  YES  NO  DB
  YES YES  DB
  YES YES  DB

但是输出不是我想要的

  DB  DL NEW
  NO  NO  NO
  NO  NO  NO
  NO YES  DL
  NO YES  DL
  YES  NO  DB
  YES  NO  DB
  YES YES  DBL
  YES YES  DBL

预期的输出是

internal/modules/cjs/loader.js:583
    throw err;
    ^

Error: Cannot find module 'cli-cursor'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (C:\Users\mrkinix\AppData\Roaming\npm\node_modules\@vue\cli\node_modules\inquirer\lib\prompts\list.js:9:17)    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
PS D:\New folder>

3 个答案:

答案 0 :(得分:3)

嵌套的ifelse()语句很快就会变得笨拙,请尝试一下dplyr::case_when()

data.frame(
  DB = c("NO","NO","NO","NO",'YES','YES','YES','YES'),
  DL = c("NO","NO","YES","YES",'NO','NO','YES','YES')
) -> mydat

dplyr::mutate(
  mydat, NEW = dplyr::case_when(
    ((DB == "YES") & (DL == "YES")) ~ "DBL",
    DB == "YES" ~ "DB",
    DL == "YES" ~ "DL",
    TRUE ~ "NO"
  )
)
##    DB  DL NEW
## 1  NO  NO  NO
## 2  NO  NO  NO
## 3  NO YES  DL
## 4  NO YES  DL
## 5 YES  NO  DB
## 6 YES  NO  DB
## 7 YES YES DBL
## 8 YES YES DBL

如果您想坚持使用基数R,只需重新排列条件:

with(
  mydat,
  ifelse(
    ((DB == "YES") & (DL == "YES")), "DBL",
    ifelse(
      (DB == "YES"), "DB",
      ifelse(
        (DL == "YES"), "DL", "NO"
      )
    )
  )
) -> mydat$NEW

答案 1 :(得分:2)

mydat$NEW <-    
c("NO","DL","DB","DBL")[apply(mydat, 1 , function(x) sum(x == "YES") + (x[1] == "YES") + 1)]

#   DB  DL NEW
#1  NO  NO  NO
#2  NO  NO  NO
#3  NO YES  DL
#4  NO YES  DL
#5 YES  NO  DB
#6 YES  NO  DB
#7 YES YES DBL
#8 YES YES DBL

答案 2 :(得分:1)

如果您想知道为什么它不起作用,那是由逻辑路径引起的。

在最后情况

ifelse(mydat$DB=="YES" & mydat$DL=="YES","DBL", "NO")

仅在

时输入
 mydat$DL=="YES"

为假,因此此条件永远不适用。

如果要使用嵌套的if_elses尝试,请尝试:

mydat$NEW <- ifelse(mydat$DB=="YES"  & mydat$DL=="YES","DBL", 
                  ifelse(mydat$DL=="YES", "DL",
                         ifelse(mydat$DB=="YES","DB", "NO")))

此外,如果您选择了 dplyr if_else,则原因是更安全并且是一种很好的做法。