在R中跨多个列标记不同的组合

在R中跨多个列标记不同的组合,r,tidyverse,R,Tidyverse,我想创建一个新列,用于标记跨x、y、z列的每个唯一值组合。我目前的工作目标是: > library(tidyverse) > > set.seed(100) > df = tibble(x = sample.int(5, 50, replace = T), y = sample.int(5, 50, replace = T), z = sample.int(5, 50, replace = T)) > df # A tibble: 50 x 3 x

我想创建一个新列,用于标记跨
x
y
z
列的每个唯一值组合。我目前的工作目标是:

> library(tidyverse) 
> 
> set.seed(100)
> df = tibble(x = sample.int(5, 50, replace = T), y = sample.int(5, 50, replace = T), z = sample.int(5, 50, replace = T))
> df
# A tibble: 50 x 3
       x     y     z
   <int> <int> <int>
 1     2     4     4
 2     3     4     4
 3     1     3     5
 4     2     1     4
 5     4     2     5
 6     4     5     2
 7     2     3     4
 8     3     5     4
 9     2     4     1
10     5     5     2
# … with 40 more rows
> 
> df2 = df %>% distinct(x,y,z) %>% rowid_to_column("unique_id") %>% left_join(df)
Joining, by = c("x", "y", "z")
> df2
# A tibble: 50 x 4
   unique_id     x     y     z
       <int> <int> <int> <int>
 1         1     2     4     4
 2         2     3     4     4
 3         3     1     3     5
 4         4     2     1     4
 5         4     2     1     4
 6         5     4     2     5
 7         5     4     2     5
 8         6     4     5     2
 9         6     4     5     2
10         7     2     3     4
# … with 40 more rows
>库(tidyverse)
> 
>种子集(100)
>df=tibble(x=sample.int(5,50,replace=T),y=sample.int(5,50,replace=T),z=sample.int(5,50,replace=T))
>df
#一个tibble:50x3
x y z
1     2     4     4
2     3     4     4
3     1     3     5
4     2     1     4
5     4     2     5
6     4     5     2
7     2     3     4
8     3     5     4
9     2     4     1
10     5     5     2
#…还有40行
> 
>df2=df%%>%不同(x,y,z)%%>%rowid\u to\u列(“唯一的\u id”)%%>%left\u join(df)
连接,通过=c(“x”、“y”、“z”)
>df2
#一个tibble:50x4
唯一_id x y z
1         1     2     4     4
2         2     3     4     4
3         3     1     3     5
4         4     2     1     4
5         4     2     1     4
6         5     4     2     5
7         5     4     2     5
8         6     4     5     2
9         6     4     5     2
10         7     2     3     4
#…还有40行

在相当大的数据集上执行此操作的更好/更有效的方法是什么?我想呆在
tidyverse
内,但也愿意接受其他建议。

您可以从
数据中使用
rleidv
。表

df$unique_id <- data.table::rleidv(df)
library(data.table)
setDT(df)[, unique_id := .GRP, names(df)]

您可以从
data.table

df$unique_id <- data.table::rleidv(df)
library(data.table)
setDT(df)[, unique_id := .GRP, names(df)]

dplyr
devel
版本中,我们可以使用
cur\u group\u id

library(dplyr)
df %>%
     group_by_all() %>% 
     mutate(unique_id = cur_group_id())
或者使用
数据表中的
.GRP

df$unique_id <- data.table::rleidv(df)
library(data.table)
setDT(df)[, unique_id := .GRP, names(df)]

dplyr
devel
版本中,我们可以使用
cur\u group\u id

library(dplyr)
df %>%
     group_by_all() %>% 
     mutate(unique_id = cur_group_id())
或者使用
数据表中的
.GRP

df$unique_id <- data.table::rleidv(df)
library(data.table)
setDT(df)[, unique_id := .GRP, names(df)]