我正在尝试根据几个条件进行关键词搜索。我的下面的代码创建了一些示例数据,并尝试通过它。它不喜欢ifelse,我相信因为GREP实际上并不返回真/假,而是实际数据。我想我必须创建一个子集,然后将其合并回去?但是,我似乎无法在带有GREP的子集中放置多个条件。
非常感谢任何帮助!
bus_name <- c('jacks wok shop'
,'jacks ski shop'
,'jacks wokshop'
,'jacks bakery'
,'jacks business'
,'jims Brewery'
,'jims Wok Brewery'
)
type <- c('restaurant'
,'restaurant'
,'restaurant'
,'restaurant'
,'office'
,'store'
,'building'
)
mydata <- data.frame(bus_name, type)
mydata$bus_name <- as.character(mydata$bus_name)
mydata$type <- as.character(mydata$type)
mydata$flag <- ifelse(mydata$type == "restaurant" & mydata[grep("WOK",toupper(mydata$bus_name)),],"Wok",
ifelse(mydata$type == "office" & mydata[grep("BUSINESS",toupper(mydata$bus_name)),],"Business","0"))
理想的输出如下:
bus_name|type|flag
jacks wok shop|restaurant|Wok
jacks ski shop|restaurant
jacks wokshop|restaurant|Wok
jacks bakery|restaurant
jacks business|office|Business
jims Brewery|store
jims Wok Brewery|building|Wok
答案 0 :(得分:2)
您必须使用if($result->num_rows > 0) {
// you now know there are results
while ($row = mysqli_fetch_assoc($result)) {
// do your business in here as you would have, but you dont need to worry about nothing to process
}
} else {
// do something in here to send back a null result, or whatever you like
}
来获取TRUE / FALSE的逻辑向量。您可以使用grepl
中的case_when
。它比嵌套的dplyr
更容易阅读。
ifelse
答案 1 :(得分:1)
grepl
是要使用的函数。你需要这样的东西
mydata$flag <- ifelse(mydata$type == "restaurant" & grepl("WOK",toupper(mydata$bus_name)),
"Wok",
ifelse(mydata$type == "office" & grepl("BUSINESS",toupper(mydata$bus_name)),
"Business",""))