如何按组创建计数器/计数? [英] How to create a counter/numeration by group?

查看:118
本文介绍了如何按组创建计数器/计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些形状如下的数据:

I've got some data in the following shape:

更新:我的数据还有一个额外的变量,我想对其进行分组。我将ddply用于Richie提供的以下解决方案,但没有用。

UPDATE: My data has an extra variable I'd like to group by. I used ddply with the below solution provided by Richie but did not work.

Country,group, date
US,A,'2011-10-01'
US,B,'2011-10-01'
US,C,'2011-10-01'
MX,D,'2011-10-01'
UK,E,'2011-10-02'
UK,B,'2011-10-02'
UK,A,'2011-10-02'
UK,C,'2011-10-02'

数据框已订购A排在第一位,B排在第二位,依此类推。我要创建的是按日期排列的排名变量,如下所示:

The data frame is already ordered so A came first, B second and so on so forth. What I am trying to create is a rank variable by date like this:

Country,group, date,rank
US,A,'2011-10-01',1
US,B,'2011-10-01',2
US,C,'2011-10-01',3
MX,D,'2011-10-01',1
UK,E,'2011-10-02',1
UK,B,'2011-10-02',2
UK,A,'2011-10-02',3
UK,C,'2011-10-02',4
    ....


推荐答案

首先,检查您的日期是否确实是日期格式(不是使用 class(your_dataset $ date)的因素)。如果不是,请使用 lubridate 中的 ymd 进行转换。

First, check that your date really is in a date format (not a factor) using class(your_dataset$date). IF not, use ymd from lubridate to convert it.

第二,使用 rank 获得排名。 (比您想象的还容易,对!)

Second, use rank to get the rank. (Easier than you think, right!)

您的数据集$ rank<-rank(您的数据集日期)

您可能想探索几种打破平局的方法。

重新阅读您的问题后,我看到您不想对日期进行排名,而是想要在日期内添加一个计数器。为此,请首先检查您的数据集是否按日期排序。

Upon rereading your question, I see you don't want to rank the dates, you want a counter within the dates. To do this, first check that your dataset is ordered by date.

o <- with(your_dataset, order(date))
your_dataset <- your_dataset[o, ]

然后调用 seq_len

counts <- as.numeric(table(your_dataset$date))
your_dataset$rank <- unlist(lapply(counts, seq_len))

这篇关于如何按组创建计数器/计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆