2017-08-31 97 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