>我在下面有数据帧
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)
我想创建一个新变量,如果字符串中同时包含Washer
和Dryer
,它将包含数字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