意外输入 \ 不允许在字符串中标识字符



>我在下面有数据帧

string<-"["TV", "Hair dryer","Dryer", "Heating", "Kitchen", "Wifi", "Air conditioning", "Hangers", "Washer", "Iron", "Elevator", "Essentials"]"                                                                                          
string2<-"["TV", "Hair dryer", "Heating", "Kitchen", "Wifi", "Air conditioning", "Hangers", "Washer", "Iron", "Elevator", "Essentials"]"                                                                                          
value<-c(string,string2)
name<-c("hOUSE","HOUSE2")
D<-data.frame(value,name)

我想创建一个新变量,如果字符串中同时包含WasherDryer,它将包含数字1,否则它将包含0.我正在尝试:

D$WasherDryer <- ifelse(str_detect(D$value, "Washer" && "Dryer"), 1, 0)

但它行不通。如何更换此

map中将单词作为向量传递更容易,并且与&reduce

library(dplyr)
library(purrr)
library(stringr)
D <- D %>%
mutate(WasherDryer = map_int(c("Washer", "Dryer"), 
~ str_detect(value, .x) %>% 
reduce(`&`) %>% 
as.integer))

-输出

D                                                                                                                               #value
#1 ["TV", "Hair dryer","Dryer", "Heating", "Kitchen", "Wifi", "Air conditioning", "Hangers", "Washer", "Iron", "Elevator", "Essentials"]
#2         ["TV", "Hair dryer", "Heating", "Kitchen", "Wifi", "Air conditioning", "Hangers", "Washer", "Iron", "Elevator", "Essentials"]
#    name WasherDryer
#1  hOUSE           1
#2 HOUSE2           0

或者,如果我们想使用正则表达式,请确保有两个选择 - 1) "洗衣机"一词可以放在"烘干机"之前,也可以成功,以便可以检查这两种情况

D$WasherDryer <- as.integer(str_detect(D$value, "\bWasher\b.*\bDryer\b|\bDryer\b.*\bWasher\b"))
D$WasherDryer
#[1] 1 0

相关内容

  • 没有找到相关文章

最新更新