Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table create dummy column which map existed column

I want to create a dummy numeric column which map 1-1 with existed character column to run correlation

My table look like:

Code
US
UK
VN
US
VN
UK

I want to have new column dummy which map US, UK, VN to 1, 2, 3

Code     dummy
US       1
UK       2
VN       3
US       1
VN       3
UK       2

Hope someone can help!

like image 816
Minh Ha Pham Avatar asked Nov 29 '25 01:11

Minh Ha Pham


1 Answers

Or you can simply use the built in .GRP function

DT[, dummy := .GRP, by = Code][]
#    Code dummy
# 1:   US     1
# 2:   UK     2
# 3:   VN     3
# 4:   US     1
# 5:   VN     3
# 6:   UK     2
like image 121
David Arenburg Avatar answered Nov 30 '25 15:11

David Arenburg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!