試圖找到類似的帖子,但不能。如何唯一索引列?
我在數據表中的列,看起來像這樣 - 來索引>
x,x,x,x,y,y,y,c,c,c
我想在一個單獨的列,使得 - >
1,1,1,1,2,2,2,3,3,3
怎麼辦呢?
試圖找到類似的帖子,但不能。如何唯一索引列?
我在數據表中的列,看起來像這樣 - 來索引>
x,x,x,x,y,y,y,c,c,c
我想在一個單獨的列,使得 - >
1,1,1,1,2,2,2,3,3,3
怎麼辦呢?
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
與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
我去與此,這具有的優點與數據幀和dat一起工作一張桌子,(也許蹣跚,idk)。索引號是從col
代碼的第一次出現獲得的,並且輸出索引號不依賴於col
代碼是相鄰行(所以如果col
去x,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
真正的重複是在這裏:https://stackoverflow.com/questions/6112803/how-to-create-a-consecutive-index-based-on-a-grouping-variable-in-a-dataframe – Spacedman