如标题所示,我正在尝试在中创建一列,data.table
该列将用作另一列的唯一标识符。我的数据集是几亿个观测值,但是这是我迄今为止编写的一组游戏和代码:
# I use a key because there are many more columns, but they are irrelevant here
myDT <- data.table(Addy=c("12hig", "12hig", "12hig", "1AbHN", "198aM"),key="Addy")
Addy
1: 12hig
2: 12hig
3: 12hig
4: 198aM
5: 1AbHN
uniqueDT <- unique(myDT[,list(Addy)]) # is this inefficient?
uniqueDT[,mrpId := seq(1,nrow(uniqueDT),1)]
Addy mrpId
1: 12hig 1
2: 198aM 2
3: 1AbHN 3
myDT[J(uniqueDT)]
Addy mrpId
1: 12hig 1
2: 12hig 1
3: 12hig 1
4: 198aM 2
5: 1AbHN 3
我上面的代码可以完成工作,但是我真的不知道它是否有效。有没有更data.table
特别的方式呢?
编辑:
您可能想知道为什么我要根据唯一标识符创建唯一标识符。好吧,这里的想法是基本上创建一个哈希。“ Addy”列数据是很长的字符串,因此我需要对此数据进行操作,因此我认为最好使用较少的字节数。
这应该很快,并且至少要简单一些:
myDT[, mrpID:=.GRP, by=Addy]
myDT
Addy mrpID
1: 12hig 1
2: 12hig 1
3: 12hig 1
4: 198aM 2
5: 1AbHN 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句