Home > OS >  How to use the match and unique functions with multiple criteria in R?
How to use the match and unique functions with multiple criteria in R?

Time:03-10

I have a dataset (Site) in the format below without column Z. I want to create a third column in R such that column Y will display as shown in column Z. I used the match function but did not get the desired result:

Site$Z <- match(Site$Y, unique(Site$Y))

X   Y   Z
A   1   1
A   1   1
A   1   1
A   2   2
A   2   2
A   2   2
B   1   3
B   1   3
B   1   3
B   2   4
B   2   4
B   2   4
B   3   5
B   3   5
B   3   5
B   3   5
B   4   6
B   4   6

CodePudding user response:

Here are a couple options:

## base R
Site$Z = with(Site, as.integer(interaction(X, Y)))

## dplyr
library(dplyr)
Site = Site %>%
  group_by(X, Y) %>%
  mutate(Z = cur_group_id()) %>%
  ungroup()

## data.table
library(data.table)
setDT(Site)
Site[, Z := .GRP, by = c("X", "Y")]

CodePudding user response:

Here are some options in collapse

library(collapse)
Site$Z <- groupid(finteraction(slt(Site, X, Y)))

Or

Site$Z <-  as.integer(finteraction(slt(Site, X, Y)))
Site$Z
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 5 6 6

Or with qG

qG(finteraction(slt(Site, X, Y)))
#[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 5 6 6

Or the base R option with paste

tmp <- with(Site, paste(X, Y))
Site$Z <- match(tmp, unique(tmp))
  •  Tags:  
  • r
  • Related