Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在data.table中使用unique,但跟踪原始行(例如,unique,然后匹配)_R_Data.table_Match_Unique - Fatal编程技术网

R 在data.table中使用unique,但跟踪原始行(例如,unique,然后匹配)

R 在data.table中使用unique,但跟踪原始行(例如,unique,然后匹配),r,data.table,match,unique,R,Data.table,Match,Unique,我向这个美好的社区提出的第一个问题是: 我想知道是否有更有效的方法,但使用data.table: # vector example all <- c(4,4,2,1,2) (uniq <- unique(all)) ## [1] 4 2 1 match(all,uniq) ## [1] 1 1 2 3 2 以下是使用数据的可能方法。表版本1.12.4: DT[, urow := unique(DT)[DT, on=.NATURAL, which=TRUE]] 输出: V1

我向这个美好的社区提出的第一个问题是:

我想知道是否有更有效的方法,但使用data.table:

# vector example
all <- c(4,4,2,1,2)
(uniq <- unique(all))
## [1] 4 2 1
match(all,uniq)
## [1] 1 1 2 3 2

以下是使用
数据的可能方法。表
版本1.12.4:

DT[, urow := unique(DT)[DT, on=.NATURAL, which=TRUE]]
输出:

   V1 V2 urow
1:  7  5    1
2:  5  6    2
3:  6  5    3
4:  7  6    4
5:  7  7    5
6:  7  6    4
7:  7  5    1
8:  6  6    6
数据:

library(data.table)#data.table_1.12.4
结实种子(9L)

DT在
DT.uniq

dt[dt.uniq[, row := seq_len(.N)], on = c('V1', 'V2')]

#   V1 V2 row
#1:  5  7   1
#2:  5  7   1
#3:  5  5   2
#4:  5  5   2
#5:  5  5   2
#6:  6  7   3
#7:  6  6   4
#8:  6  6   4
数据

library(data.table)
m <- matrix(c(5, 5, 5, 5, 6, 5, 6, 6, 7, 7, 5, 5, 7, 5, 6, 6), nrow = 8, ncol = 2)
dt <- setDT(as.data.frame(m)) 
dt.uniq <- unique(dt)
库(data.table)

m你想要的输出是什么?你的数据是不可复制的…谢谢你的反馈。我编辑了数据,并添加了一条关于我的愿望的注释。在dt中保持原始行顺序的方法是什么?输出按列“行”排序,这在更新data.table包后工作得非常好。只是想知道,你能给我解释一下,
on=.NATURAL
which=TRUE
是做什么的吗?@Fernando.-,我编辑了这篇文章来解决你的问题。
dt[dt.uniq[, row := seq_len(.N)], on = c('V1', 'V2')]

#   V1 V2 row
#1:  5  7   1
#2:  5  7   1
#3:  5  5   2
#4:  5  5   2
#5:  5  5   2
#6:  6  7   3
#7:  6  6   4
#8:  6  6   4
library(data.table)
m <- matrix(c(5, 5, 5, 5, 6, 5, 6, 6, 7, 7, 5, 5, 7, 5, 6, 6), nrow = 8, ncol = 2)
dt <- setDT(as.data.frame(m)) 
dt.uniq <- unique(dt)