R中的SQLDF左连接

4

我的目标是对“matr”进行排序,按列c1排序,并保留其中满足c2 = 1的唯一值(c1)。例如,从以下代码...

c1 = c("a",'a','a','b','b','b','b','c','c')
c2 = c(1,1,0,1,1,0,1,0,0)
matr = as.data.frame(cbind(c1,c2))    
one = sqldf('select distinct(c1),c2 from matr where c2 = 1')    
vs = sqldf('select distinct(c1),c0,c2 from matr group by c1')
sqldf('select matr.*,one.* from matr 
  left outer join one 
  where one.c1 = matr.c1')

到达:

c1 c2
a  1
b  1
c  0

由于某些原因,在左连接中我失去了行c。我只能通过其他连接到达(此结果)。
c1 c2
a  1
b  1
1个回答

5

在最后的SQL语句中,您需要使用on而不是where。使用where会先执行连接,然后再应用where子句,而使用on则根据on条件进行连接。

> sqldf('select matr.*, one.* from matr left outer join one on one.c1 = matr.c1')
  c1 c2   c1   c2
1  a  1    a    1
2  a  1    a    1
3  a  0    a    1
4  b  1    b    1
5  b  1    b    1
6  b  0    b    1
7  b  1    b    1
8  c  0 <NA> <NA>
9  c  0 <NA> <NA>

谢谢你的回答!它帮助我解决了一个我一直在苦苦挣扎的问题。 - Gyan Veda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接