如何在 R 中的 SQLDF 中使用 LIKE 在多个数据框中搜索文本
How to use LIKE in SQLDF in R for searching text in multiple dataframes
我有 2 个带有文本的数据框,想比较部分字符串。
我正在寻找的是 table 2.
中的 ID、t1.mo 和 monthid
t1 <- data.frame("id"=1:4,"mo"=c("Jan","Feb","Apr","Mar"))
t2 <- data.frame("id"=1:4, "nt"= c("January","Jan Feb","February","Mar"),"monthid" = 5:8)
sqldf("select t1.mo,t2.nt,t2.monthid from t1, t2 where t1.mo like '%' || t2.nt || '%'")
我试过了,
sqldf("select t1.mo,t2.mo from t1, t2 where t1.mo like '%Feb%'")
及其工作
但是当引用 t2
时它不起作用。
T1.id t1.mo t2.monthid
1 Jan 5
2 Feb 6
4 Mar 8
感谢任何帮助。
编辑了 Tim Biegeleisen 指出的输出。
您正在向后进行 LIKE
比较,您应该检查 t1
中的 mo
列是否作为 nt
列的子字符串出现在 t2
:
sql <- "SELECT t1.mo, t2.nt, t2.monthid
FROM t1
INNER JOIN t2 ON t2.nt like '%' || t1.mo || '%' AND t1.id = t2.id"
result <- sqldf(sql)
另请注意,我已重构您的查询以使用适当的 显式 连接,这是编写 SQL.
的首选方式
请注意,我在结果集中获得了超出您预期的额外记录,但这是因为第一个 table 中的 Feb
匹配 Jan Feb
和 February
在第二个 table 中。如果您只希望在那里进行一场比赛,您应该说明原因。
我有 2 个带有文本的数据框,想比较部分字符串。 我正在寻找的是 table 2.
中的 ID、t1.mo 和 monthidt1 <- data.frame("id"=1:4,"mo"=c("Jan","Feb","Apr","Mar"))
t2 <- data.frame("id"=1:4, "nt"= c("January","Jan Feb","February","Mar"),"monthid" = 5:8)
sqldf("select t1.mo,t2.nt,t2.monthid from t1, t2 where t1.mo like '%' || t2.nt || '%'")
我试过了,
sqldf("select t1.mo,t2.mo from t1, t2 where t1.mo like '%Feb%'")
及其工作
但是当引用 t2
时它不起作用。
T1.id t1.mo t2.monthid
1 Jan 5
2 Feb 6
4 Mar 8
感谢任何帮助。
编辑了 Tim Biegeleisen 指出的输出。
您正在向后进行 LIKE
比较,您应该检查 t1
中的 mo
列是否作为 nt
列的子字符串出现在 t2
:
sql <- "SELECT t1.mo, t2.nt, t2.monthid
FROM t1
INNER JOIN t2 ON t2.nt like '%' || t1.mo || '%' AND t1.id = t2.id"
result <- sqldf(sql)
另请注意,我已重构您的查询以使用适当的 显式 连接,这是编写 SQL.
的首选方式请注意,我在结果集中获得了超出您预期的额外记录,但这是因为第一个 table 中的 Feb
匹配 Jan Feb
和 February
在第二个 table 中。如果您只希望在那里进行一场比赛,您应该说明原因。