Regex R:基于匹配一个或多个可能的字符串,在数据帧中填充新列
假设数据帧:Regex R:基于匹配一个或多个可能的字符串,在数据帧中填充新列,regex,r,dataframe,pattern-matching,match,Regex,R,Dataframe,Pattern Matching,Match,假设数据帧: strings new column mesh 1 foo 0 bar 0 tack 1 suture 1 如果df$strings包含字符串mesh、tack或sutur,我希望新列包含1。否则,它应在同一行中显示零。我尝试了以下方法: df$new_column <- ifelse(grepl("mesh" | "tack" | "sutur", df$strings, ign
strings new column
mesh 1
foo 0
bar 0
tack 1
suture 1
如果df$strings包含字符串mesh、tack或sutur,我希望新列包含1。否则,它应在同一行中显示零。我尝试了以下方法:
df$new_column <- ifelse(grepl("mesh" | "tack" | "sutur",
df$strings, ignore.case = T), "1", "0")
提前感谢。您想在grep中使用单个字符串: 将起作用,但以下操作将更快:
df$new_column <- +(grepl("mesh|tack|sutur", df$strings, ignore.case = T))
这将返回一个0和1的整数向量我们也可以使用%in%
df$new_column <- ifelse(grepl("mesh|tack|sutur", df$strings, ignore.case = T),
"1", "0")
df$new_column <- +(grepl("mesh|tack|sutur", df$strings, ignore.case = T))
df$new_column <- as.integer(df$strings %in% c("mesh", "tack", "sutur"))