计算单个列中的值

时间:2012-01-17 20:06:48

标签: r

我正在使用R中的sqldf包,并且我试图在单个列中查找值为1和2的值。我的数据如下:

> head(d)
       bid status
1  201-300      1
2  201-300      1
3 901-1000      2
4  601-700      1
5  801-900      1
6  801-900      2

我试图在等于1时找到状态计数,当它等于2时找到状态计数,然后将它们放在两个单独的列中。

因此,使用R中的sqldf包,我运行了以下代码:

sqldf("SELECT bid, SUM(IF(status='2', 1,0)) AS 'won', SUM(IF(status='1', 1,0)) AS 'lost', COUNT(bid) FROM d GROUP BY bid")

但是,我收到以下错误消息。

Error in sqliteExecStatement(con, statement, bind.data) : 
  RS-DBI driver: (error in statement: no such function: IF)

sqldf包无法实现这一点吗? 有没有办法在R中使用另一个sql命令获得所需的结果? (或使用plyr,reshape或R中的任何其他工具)

6 个答案:

答案 0 :(得分:4)

IF具有MySQL特定语法,而错误表明您正在与SQLite数据库通信。

您应该将IF替换为CASE,这将适用于符合ANSI SQL-92的所有DMBS。

SELECT  bid
        , SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS won
        , SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS lost
FROM    d
GROUP BY
        bid

答案 1 :(得分:2)

正常的SQL是使用CASESUM - 我不做MySQL,但我认为这应该是有效的语法:

SELECT SUM(CASE WHEN Status = '2' THEN 1 ELSE 0 END) as 'won',
       SUM(CASE WHEN Status = '1' THEN 1 ELSE 0 END) as 'lost',
...

答案 2 :(得分:2)

编辑:问题被标记为mysql,但我不确定是不是这样

看看MySQL Control Flow Functions。您可以使用IF构造(特定于MySQL)或CASE WHEN(ANSI兼容)运算符:

SELECT
bid,
SUM(IF(status = 2, 1, 0)) AS `won`,
SUM(IF(status = 1, 1, 0)) AS `lost`,
COUNT(bid)
FROM d
GROUP BY bid


SELECT
bid,
SUM(CASE status WHEN 2 THEN 1 ELSE 0 END) AS `won`,
SUM(CASE status WHEN 1 THEN 1 ELSE 0 END) AS `lost`,
COUNT(bid)
FROM d
GROUP BY bid

答案 3 :(得分:1)

既然你说你可能对基于plyr的解决方案感兴趣,我可以给出:

ddply(d, .(bid), summarise, won = sum(status==2), 
                            lost = sum(status==1), count = length(bid))

答案 4 :(得分:1)

if无效SQLite syntax。试试这个:

> sqldf("select bid, sum(status=1) lost, sum(status=2) won, count(*) count 
+ from d group by bid")
       bid lost won count
1  201-300    2   0     2
2  601-700    1   0     1
3  801-900    1   1     2
4 901-1000    0   1     1

答案 5 :(得分:0)

试试这个:

select count(bid) as 'bid_status_1' from d where bid_status = 1 union select count(bid) as 'bid_status_2'from d where bid_status = 2