R中的条件值赋值
在以下示例数据中:R中的条件值赋值,r,dataframe,data-manipulation,R,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
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)
关键字
#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"] = ""
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"
df[grepl("advertising plan|advertising budget", df$keyword), "Topic"] = "Advertising"
df[grepl("marketing plan|marketing budget", df$keyword), "Topic"] = "Marketing"