R:如何使用if else条件创建两个变量

时间:2018-03-14 06:19:17

标签: r

假设我有数据集包含两个变量 -

Name              Name2
Dr John           Apollo Hsp
AIIMS Hsp      Dr Khan

现在我希望根据条件创建另外两个变量,当名称以Dr开头时将转到医生专栏,当它不以Dr开头时,它将转到设施专栏。

输出:

Name              Name2           facility            Physician
Dr John           Apollo Hsp.   Apollo Hsp.   Dr John
AIIMS Hsp      Dr Khan.        AIIMS Hsp.    Dr Khan.

1 个答案:

答案 0 :(得分:1)

我们可以在ifelse使用grepl

df <- data.frame(Name=c("Dr John", "AIIMS Hsp"),
                 Name2=c("Apollo Hsp", "Dr Khan."), stringsAsFactors=FALSE)

df$facility  <- ifelse(grepl("^Dr", df$Name), df$Name2, df$Name)
df$Physician <- ifelse(grepl("^Dr", df$Name), df$Name, df$Name2)
df

       Name      Name2   facility Physician
1   Dr John Apollo Hsp Apollo Hsp   Dr John
2 AIIMS Hsp   Dr Khan.  AIIMS Hsp  Dr Khan.

Demo