在两列之间的dplyr中过滤,其中一列是列表或向量

时间:2018-04-18 19:55:51

标签: r dplyr strsplit

尝试通过比较prod列中存在lob的这两列来尝试过滤此df:

可重现的代码:

df <- data.frame(prod = c("CES", "Access", "Access", "CES"), lob = c("Access;Entertainment", "CES", "Access", "Access;Entertainment;CES"))

    prod                      lob
1    CES     Access;Entertainment
2 Access                      CES
3 Access                   Access
4    CES Access;Entertainment;CES

预期结果:

    prod                      lob
1 Access                   Access
2    CES Access;Entertainment;CES

我尝试将lob列拆分为向量或包含元素的列表,然后将dplyr filtergrepl(prod, lob)prod %in% lob一起使用,但似乎都不起作用

df %>%
filter(prod %in% lob)

df %>%
mutate(lob = strsplit(lob, ";")) %>%
filter(prod %in% lob)

df %>%
mutate(lob = strsplit(lob, ";")) %>%
filter(grepl(prod), lob)

2 个答案:

答案 0 :(得分:4)

在那里添加rowwise()

可能最简单
df %>%
  mutate(lob = strsplit(lob, ";")) %>% 
  rowwise() %>% 
  filter(prod %in% lob) %>% 
  as.data.frame() # rowwise makes it a tibble, this changes it back if needed

如果你真的不想做mutate(),你可以做

df %>%
  rowwise() %>% 
  filter(prod %in% strsplit(lob, ";")[[1]])

答案 1 :(得分:1)

使用buildTypes { release { ... ... ... } } android.enforceUniquePackageName = false

stringr::str_detect