Home > OS >  How to create a column based on repeated values in other columns?
How to create a column based on repeated values in other columns?

Time:10-13

So basically I have a data frame that looks like this:

BX BY
4.1 12.4
4.1 12.4
4.1 12.4
10.0 14.5
10.0 14.5
9.7 5.6

The BX and BY variables are coordinates, I want to create an ID column which will be the same for every point with the same coordinates, and it should like this:

BX BY ID
4 12 1
4 12 1
4 12 1
10 14 2
10 14 2
9 5 3

CodePudding user response:

With dplyr...

library(dplyr)

df1 |> 
  group_by(BX, BY) |> 
  mutate(ID = cur_group_id())
#> # A tibble: 6 × 3
#> # Groups:   BX, BY [3]
#>      BX    BY    ID
#>   <dbl> <dbl> <int>
#> 1     4    12     1
#> 2     4    12     1
#> 3     4    12     1
#> 4    10    14     3
#> 5    10    14     3
#> 6     9     5     2

data

df1 <- structure(list(BX = c(4, 4, 4, 10, 10, 9), 
                      BY = c(12, 12, 12,14, 14, 5)), 
                 class = c("tbl_df", "tbl", "data.frame"), 
                 row.names = c(NA, -6L))

Created on 2022-10-13 with reprex v2.0.2

CodePudding user response:

With data.table:

library(data.table)
setDT(df)
df[, id := .GRP, by = .(bx, by)]
setDF(df)
  •  Tags:  
  • r
  • Related