创建一个列并根据R

时间:2017-01-16 20:51:01

标签: r if-statement dataframe data-manipulation

这是样本数据框:

 keyword <- c("advertising plan","advertising budget",
         "marketing plan",
         "marketing budget",
         "hr plan",
         "hr budget",
         "operation plan",
         "operation budget")
 indicator <- c(1,0,1,0,0,1,1,1)
 df <- data_frame(keyword,indicator)

我需要创建一个名为“Type”的新列,如果关键字包含“advertising”或“marketing”,则将“Type A”分配给单元格,如果关键字包含“hr”,则将“Type B”分配给单元格“或”操作“。

1 个答案:

答案 0 :(得分:1)

试试这个:

df$Type = ifelse(grepl("(advertising|marketing)",df$keyword),"Type A",0)
df$Type = ifelse(grepl("(hr|operation)",df$keyword),"Type B",df$Type)

> df
             keyword indicator   Type
1   advertising plan         1 Type A
2 advertising budget         0 Type A
3     marketing plan         1 Type A
4   marketing budget         0 Type A
5            hr plan         0 Type B
6          hr budget         1 Type B
7     operation plan         1 Type B
8   operation budget         1 Type B