R:在列中创建组

时间:2016-10-06 18:00:44

标签: r

我正在尝试将年龄列分组到年龄组列中,并按该分组进行汇总。

即我需要下面的数据集 -

AGE
1
2
5
68
27
4
2
33
45

成为

AGE_GRP COUNT
1-10     5
11-20    0
21-30    1
31-40    1
40+      2

我正在使用R

感谢。

2 个答案:

答案 0 :(得分:1)

您需要CASE语句将AGE拆分为不同的组

SELECT CASE
         WHEN AGE BETWEEN 1 AND 10 THEN '1-10'
         WHEN AGE BETWEEN 11 AND 20 THEN '11-20'
         WHEN AGE BETWEEN 21 AND 30 THEN '21-30'
         WHEN AGE BETWEEN 31 AND 40 THEN '31-40'
         ELSE '40+'
       END AS AGE_GRP,
       Count(1) as Cnt
FROM   yourtable
GROUP  BY CASE
            WHEN AGE BETWEEN 1 AND 10 THEN '1-10'
            WHEN AGE BETWEEN 11 AND 20 THEN '11-20'
            WHEN AGE BETWEEN 21 AND 30 THEN '21-30'
            WHEN AGE BETWEEN 31 AND 40 THEN '31-40'
            ELSE '40+'
          END 

如果您不想在CASE中重复GROUP BY声明,请使用此

SELECT AGE_GRP,
       Count(1) AS cnt
FROM   (SELECT CASE
                 WHEN AGE BETWEEN 1 AND 10 THEN '1-10'
                 WHEN AGE BETWEEN 1 AND 10 THEN '11-20'
                 WHEN AGE BETWEEN 1 AND 10 THEN '21-30 '
                 WHEN AGE BETWEEN 1 AND 10 THEN '31-40'
                 ELSE '40+'
               END AS AGE_GRP
        FROM   yourtable) A
GROUP  BY AGE_GRP 

答案 1 :(得分:1)

您的值为零,因此需要left join

select agegrp, count(t.agegrp)
from (select '1-10' as agegrp, 1 as lowb, 10 as hib union all
      select '11-20' as agegrp, 11, 20 union all
      select '21-30' as agegrp, 21, 30 upperbound union all
      select '31-40' as agegrp, 31, 40 as upperbound union all
      select '40+' as agegrp, 41, NULL as upperbound
     ) ag left join
     t
     on t.age >= ag.lowb and t.age <= ag.hib
group by ag.agegrp
order by ag.lowb;

注意:这假设列是整数,因此不允许使用类似30.5的值。如果需要,可以很容易地调整查询以处理非整数年龄。