Reputation: 33
In the following the sample data:
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 <- cbind(keyword,indicator)
I need to create a new variable "Topic
". I will assign the text "Advertising
" to the cell if the keyword is "advertising plan
" and "advertising budget
"; "Marketing
" to the cell if the keyword is "marketing plan
" and "marketing budget
".
I tried to use the
df$Topic[which(df$keyword == c("advertising plan","advertising budget") <- "Advertising"
.
But it did not work out. Any help is highly appreciated!
Upvotes: 0
Views: 861
Reputation: 4836
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, stringsAsFactors = FALSE)
df[df$keyword %in% c("advertising plan", "advertising budget"), "Topic"] = "Advertising"
df[df$keyword %in% c("marketing plan", "marketing budget"), "Topic"] = "Marketing"
or, more flexible approach:
df[grepl("advertising plan|advertising budget", df$keyword), "Topic"] = "Advertising"
df[grepl("marketing plan|marketing budget", df$keyword), "Topic"] = "Marketing"
Upvotes: 1
Reputation: 32548
#Convert to dataframe if it isn't already
df = as.data.frame(df, stringsAsFactors = FALSE)
#Extract first word of the keyword as the topic
df$Topic = sapply(strsplit(df$keyword," "),function(x) x[1])
#Set all values other than marketing and advertising to blank (or NA if you want)
df$Topic[df$Topic != "marketing" & df$Topic != "advertising"] = ""
Upvotes: 1