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.