Reputation: 311
I need to create group column - B that corresponds to another column - A
DF
A B
XXL 1
XXL 1
XL 2
L 3
M 4
M 4
S 5
I was trying to use multiple ifelse
statement. But this didnt work as it returned the column of zeros. As well i tried to use vectorized way of ifelse
which resulted the same way.
Thank you for any suggestions.
Upvotes: 1
Views: 65
Reputation: 887078
We can either use match
or factor
DF$B <- with(DF, match(A, unique(A)))
DF$B
#[1] 1 1 2 3 4 4 5
Or
as.numeric(factor(DF$A, levels = unique(DF$A)))
#[1] 1 1 2 3 4 4 5
Here are some other options as well
cumsum(!duplicated(DF$A))
#[1] 1 1 2 3 4 4 5
Or with data.table
library(data.table)
setDT(DF)[, B:= .GRP, A]
Upvotes: 2