John Fox’s car library contains the recode function for recoding values of variables in a data frame. Take a hypothetical data set named food which contains information on the number of calories a person consumed over seven days. The variables in the data file are day, representing the day of the week, and calories, representing the number of calories that were consumed. The data are saved in a tab-delimited file and can thus be read into memory using the read.table command.
> food<-read.table("http//www.methodsconsultants.com/data/food.dat", header=TRUE, sep="t")
The data look like the following:
> food day calories 1 Sunday 2050 2 Monday 1800 3 Tuesday 1925 4 Wednesday 2015 5 Thursday 1875 6 Friday 3000 7 Saturday 2800
To use the recode function it is first necessary to load the car library.
Say the number of calories was recorded incorrectly for Monday and Tuesday. The following takes care of the recoding:
> food$calories<-recode(food$calories,"1800=2200; 1925=2000")
In the recode function, the name of the variable to be recoded is entered as the first argument. All recodes are then enclosed in a single set of double quotation marks and separated by semi-colons. Recoding factors works the same way, though it is necessary to use single quotation marks around string values. In addition, it is possible to recode multiple different values into a single new value. The following demonstrates:
> food$day<-recode(food$day, "c('Friday','Saturday','Sunday')='Weekend'; + else='Weekday'")
The data now look like the following:
> food day calories 1 Weekend 2050 2 Weekday 2200 3 Weekday 2000 4 Weekday 2015 5 Weekday 1875 6 Weekend 3000 7 Weekend 2800
Still have questions? Contact us!