What's the R statement responding to SQL's 'in' statement?

前端 未结 2 1129
慢半拍i
慢半拍i 2021-01-14 10:22

a case

df=data.frame(id=c(101,102,102,103,104,104,104),
         calmonth=c(\'01\',\'01\',\'01\',\'01\',\'01\',\'01\',\'02\'),
         product=c(\'         


        
2条回答
  •  时光说笑
    2021-01-14 10:58

    Your SQL statement doesn't produce quite the result you show. It returns (selects) the IDs only not that table and the merged column? No?

    SELECT id 
    FROM   df 
    WHERE  calmonth = '01' 
           AND product = "apple" 
           AND id IN (SELECT id 
                      FROM   df 
                      WHERE  product = "htc" 
                             AND calmonth = "01") 
    

    in R that is roughly:

    with(df, 
    intersect(
    id[calmonth=='01' & product=='apple'], 
    id[product=="htc" & calmonth=="01"]))
    
    [1] 102 104
    

提交回复
热议问题