测试两列字符串在R中匹配行 [英] Test two columns of strings for match row-wise in R

查看:286
本文介绍了测试两列字符串在R中匹配行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列字符串:

  library(data.table)
DT< data.table(x = c(a,aa,bb),y = c(b,a,bbb))
/ pre>

对于每一行,我想知道x中的字符串是否存在于列y中。循环方法是:

  for(i in 1:length(DT $ x)){
DT $ test [i] < - DT [i,grepl(x,y)+ 0]
}

DT
xy test
1:ab 0
2:aa a 0
3:bb bbb 1

这个?使用 grep(DT $ x,DT $ y)只使用x的第一个元素。

解决方案

您可以直接执行

  DT [,test:= grepl(x,y) x] 


Let's say I have two columns of strings:

library(data.table)
DT <- data.table(x = c("a","aa","bb"), y = c("b","a","bbb"))

For each row, I want to know whether the string in x is present in column y. A looping approach would be:

for (i in 1:length(DT$x)){
  DT$test[i] <- DT[i,grepl(x,y) + 0]
}

DT
    x   y test
1:  a   b    0
2: aa   a    0
3: bb bbb    1

Is there a vectorized implementation of this? Using grep(DT$x,DT$y) only uses the first element of x.

解决方案

You can simply do

DT[, test := grepl(x, y), by = x]

这篇关于测试两列字符串在R中匹配行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆