1

I have a larger dataset where I need to change a column numercal variable to categorical variable. A sample of the data is below:

dat1 <- read.table(header=TRUE, text="
                   ID  Pa  Gu  Ta
                   8645    1  Gel294  Tel452
                   6228    2  Gel294  Tel467
                   5830    3  Gel294  Tel467
                   1844    3  Gel295  Tel467
                   4461    4  Gel295  Tel467
                   2119    5  Gel294  Tel452
                   2119    5  Gel294  Tel452
                   ")
dat1
    ID Pa     Gu     Ta
1 8645  1 Gel294 Tel452
2 6228  2 Gel294 Tel467
3 5830  3 Gel294 Tel467
4 1844  3 Gel295 Tel467
5 4461  4 Gel295 Tel467
6 2119  5 Gel294 Tel452
7 2119  5 Gel294 Tel452

The variables in column Pa needs to be replaced by the following:

dat2 <- read.table(header=TRUE, text="
                   Pa  Abbr  
                   1    MNDF
                   2    CVDE
                   3    EEED
                   4    WERD
                   5    PPOL
                   ")
dat2
  Pa Abbr
1  1 MNDF
2  2 CVDE
3  3 EEED
4  4 WERD
5  5 PPOL

For a smaller dataset, I can do it manually by recode function in car package.

library(car)
dat1$Pa <- recode(dat1$Pa, "1='MNDF'; 2='CVDE'; 3='EEED'; 4='WERD'; 5='PPOL'")
dat1
    ID   Pa     Gu     Ta
1 8645 MNDF Gel294 Tel452
2 6228 CVDE Gel294 Tel467
3 5830 EEED Gel294 Tel467
4 1844 EEED Gel295 Tel467
5 4461 WERD Gel295 Tel467
6 2119 PPOL Gel294 Tel452
7 2119 PPOL Gel294 Tel452

I need a proper function or code that can replace the manual inputting in recode.

1 Answer 1

1

We can use match from base R

dat1$Pa <- dat2$Abbr[match(dat1$Pa, dat2$Pa)]
dat1
#    ID   Pa     Gu     Ta
#1 8645 MNDF Gel294 Tel452
#2 6228 CVDE Gel294 Tel467
#3 5830 EEED Gel294 Tel467
#4 1844 EEED Gel295 Tel467
#5 4461 WERD Gel295 Tel467
#6 2119 PPOL Gel294 Tel452
#7 2119 PPOL Gel294 Tel452
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.