【问题标题】:Create a column and assign values based on string variable in R根据 R 中的字符串变量创建列并赋值
【发布时间】:2017-01-16 20:51:00
【问题描述】:

这是示例数据框:

 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)

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

【问题讨论】:

  • 也许您可以先向我们展示您在your previous post 中的人们帮助您后获得的一些知识?

标签: r if-statement dataframe data-manipulation


【解决方案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

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2019-03-08
    • 2020-06-06
    • 2020-04-28
    • 2021-11-30
    相关资源
    最近更新 更多