2017-08-31 98 views
0

试图找到类似的帖子,但不能。如何唯一索引列?

我在数据表中的列,看起来像这样 - 来索引>

x,x,x,x,y,y,y,c,c,c 

我想在一个单独的列,使得 - >

1,1,1,1,2,2,2,3,3,3 

怎么办呢?

+0

真正的重复是在这里:https://stackoverflow.com/questions/6112803/how-to-create-a-consecutive-index-based-on-a-grouping-variable-in-a-dataframe – Spacedman

回答

0
dt$index <- cumsum(!duplicated(dt$a)) 
dt 
a index 
# 1 x  1 
# 2 x  1 
# 3 x  1 
# 4 x  1 
# 5 y  2 
# 6 y  2 
# 7 y  2 
# 8 c  3 
# 9 c  3 
# 10 c  3 
1

data.table A液:

library(data.table) 
dt <- data.table(col = c("x", "x", "x", "x", "y", "y", "y", "c", "c", "c")) 

dt[ , idx := .GRP, by = col] 
#  col idx 
# 1: x 1 
# 2: x 1 
# 3: x 1 
# 4: x 1 
# 5: y 2 
# 6: y 2 
# 7: y 2 
# 8: c 3 
# 9: c 3 
# 10: c 3 

基础R A液:

dat <- data.frame(col = c("x", "x", "x", "x", "y", "y", "y", "c", "c", "c")) 

dat <- transform(dat, idx = match(col, unique(col))) 
# col idx 
# 1 x 1 
# 2 x 1 
# 3 x 1 
# 4 x 1 
# 5 y 2 
# 6 y 2 
# 7 y 2 
# 8 c 3 
# 9 c 3 
# 10 c 3 
2

我去与此,这具有的优点与数据帧和dat一起工作一张桌子,(也许蹒跚,idk)。索引号是从col代码的第一次出现获得的,并且输出索引号不依赖于col代码是相邻行(所以如果colx,x,x,x,y,y,y,x,x,x所有x都得到索引2)。

> dt <- data.table(col = c("x", "x", "x", "x", "y", "y", "y", "c", "c", "c")) 
> dt$index = as.numeric(factor(dt$col,levels=unique(dt$col))) 
> dt 
    col index 
1: x  1 
2: x  1 
3: x  1 
4: x  1 
5: y  2 
6: y  2 
7: y  2 
8: c  3 
9: c  3 
10: c  3