使用R中的dplyr查找其中一列字符串位于另一列中的行 [英] Find rows where one column string is in another column using dplyr in R
本文介绍了使用R中的dplyr查找其中一列字符串位于另一列中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图拉回其中一列中的值作为字符串存在于另一列(同一行中)的行。
Looking to pull back rows where the value in one column exists as a string in another column (within the same row).
我有一个df:
A <- c("cat", "dog", "boy")
B <- c("cat in the cradle", "meet the parents", "boy mmets world")
df <- as.data.frame(A, B)
A B
cat cat in the cradle
dog meet the parents
boy boy meets world
我正在尝试以下操作:
df2 <- df %>%
filter(grepl(A, B)) # doesn't work because it thinks A is the whole column vector
df2 <- df %>%
filter(B %in% A) # which doesn't work because it has to be exact
我希望它产生
A B
cat cat in the cradle
boy boy meets world
谢谢!
马特
解决方案
您可以使用 Map
将函数应用于两个矢量,也可以使用 sapply
You can either apply the function to both vectors using Map
or iterate through the row using sapply
df %>%
filter(unlist(Map(function(x, y) grepl(x, y), A, B)))
A B
1 cat cat in the cradle
2 boy boy mmets world
df %>%
filter(sapply(1:nrow(.), function(i) grepl(A[i], B[i])))
A B
1 cat cat in the cradle
2 boy boy mmets world
这篇关于使用R中的dplyr查找其中一列字符串位于另一列中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文