'Create a column and assign values based on string variable in R
This is the sample data frame:
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)
I need to create a new column called "Type", and assign "Type A" to the cells if the keyword contains "advertising" or "marketing" while assign "Type B" to the cells if the keyword contains "hr" or "operation".
Solution 1:[1]
Try this:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kristofersen |
