首页 > 解决方案 > ifelse 带有可能的字符串匹配列表,没有其他

问题描述

所以通常情况下,如果我想用 1s 填充新列 data$new.col,如果它在 data$strings 中找到字符串“foo”或“bar”,如果没有,我会使用这样的东西:

data$new.col <- ifelse(grepl("foo|bar",
  data$strings, ignore.case = T, perl = T), "1", "0")

但是,我想在没有“其他”的情况下做同样的事情。我尝试使用简单的分配,但我一定做错了,因为它不起作用:

data$new.col[data$strings == "foo|bar"] <- "1"

提前致谢。

标签: rif-statement

解决方案


您需要编辑过滤条件,如下所示:

data$new.col[data$strings == "foo" | data$strings == "bar"] <- "1"

推荐阅读