use ifelse to create new column in r

霸气de小男生 提交于 2021-02-16 14:24:08

问题


My code is:

data$E<-ifelse(data$D==data$B, "b", ifelse(data$D==data$C, "c", "unknowwn"))

result:

  A   B   C   D   E
1 16  16  NA  16  b
2 20  NA  20  20  NA
3 24  NA  NA  24  NA

But what I want is:

  A   B   C   D   E
1 16  16  NA  16  b
2 20  NA  20  20  c
3 24  NA  NA  24  unknowwn

Dose anyone know how to solve this problem? Thanks!


回答1:


data$E <- ifelse(!is.na(data$B) & data$D == data$B, "b", 
            ifelse(!is.na(data$C) & data$D == data$C, "c", "unknowwn"))



回答2:


Your condition is a bit complicated as you need to consider if either of columns B, C or D contains NA. Hence, you can try consider using dplyr::case_when as:

Edited: Based on suggestion from @A.Suliman there is no need to have checking for is.na with case_when.

library(dplyr)

data %>% mutate( E = case_when(
  D==B ~ "b",
  D==C ~ "c",
  TRUE ~ "Unknown"
))

#    A  B  C  D       E
# 1 16 16 NA 16       b
# 2 20 NA 20 20       c
# 3 24 NA NA 24 Unknown

Data:

data <- read.table(text= 
"A   B   C   D   
1 16  16  NA  16  
2 20  NA  20  20
3 24  NA  NA  24",
header = TRUE)


来源:https://stackoverflow.com/questions/51348877/use-ifelse-to-create-new-column-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!