如何创建连续的组号 [英] How to create a consecutive group number

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

问题描述

我有一个数据框(all_data),其中有一个站点列表(从1 ...到n)及其得分,例如

I have a data frame (all_data) in which I have a list of sites (1... to n) and their scores e.g.

  site  score
     1    10
     1    11  
     1    12
     4    10 
     4    11
     4    11
     8    9
     8    8
     8    7

我想创建一列,以数字顺序对网站的每个级别进行编号,例如计数器.在此示例中,站点(1、4和8)在数字"列中将具有从1到3的对应计数器:

I want create a column that numbers each level of site in numerical order, like a counter. In the example, the sites (1, 4, and 8) would be have a corresponding counter from 1 to 3 in the 'number' column:

site  score number
     1    10    1
     1    11    1 
     1    12    1 
     4    10    2
     4    11    2
     4    11    2
     8    9     3
     8    8     3 
     8    7     3

我确信必须很容易解决这个问题,但是我还没有找到解决方法.

I am sure this must be easily solved, but I have not found a way yet.

推荐答案

尝试Data$number <- as.numeric(as.factor(Data$site))

在一个旁注中:一方面我和@Chase的解决方案之间的区别,另一方面,与@DWin的解决方案之间的区别是数字的排序. as.factorfactor都将自动对级别进行排序,而@DWin解决方案中不会发生这种情况:

On a sidenote : the difference between the solution of me and @Chase on one hand, and the one of @DWin on the other, is the ordering of the numbers. Both as.factor and factor will automatically sort the levels, whereas that doesn't happen in the solution of @DWin :

Dat <- data.frame(site = rep(c(1,8,4), each = 3), score = runif(9))

Dat$number <- as.numeric(factor(Dat$site))
Dat$sitenum <- match(Dat$site, unique(Dat$site) ) 

给予

> Dat
  site     score number sitenum
1    1 0.7377561      1       1
2    1 0.3131139      1       1
3    1 0.7862290      1       1
4    8 0.4480387      3       2
5    8 0.3873210      3       2
6    8 0.8778102      3       2
7    4 0.6916340      2       3
8    4 0.3033787      2       3
9    4 0.6552808      2       3

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

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