Convert a vector of integers to letters in R

My lab finished up the first wave of data collection for an RCT we’re conducting in rural Honduras, and we’re working on polishing up the dataset now that we have the final version. One of the things is making the coding consistent for multiple-response type questions, where each response to a question is encoded as a separate yes/no column. The table response_options is a list of all of the multiple-response question IDs with the option and corresponding option_code:

> head(response_options)
  new_id                            option option_code
1  f8500 Antibiotic (pill/syrup/injection)           2
2  f8300                 None of the above           4
3  f8500       Home remedy/herbal medicine           5
4  f8500                                No           1
5  f8500       Home remedy/herbal medicine           5
6  f8300                 None of the above           4

I want create a vector that will be new_id plus option_code, but letters rather than numbers. I found lots of people trying to convert a vector of letters to integers, but not the other way around and figured I’d share my solution. It’s fairly straightforward. Just pass the vector of integers (option_code here) as an index to the letters object:

> response_options$option_letter <- letters[response_options$option_code]
> head(response_options)
  new_id                            option option_code option_letter
1  f8500 Antibiotic (pill/syrup/injection)           2             b
2  f8300                 None of the above           4             d
3  f8500       Home remedy/herbal medicine           5             e
4  f8500                                No           1             a
5  f8500       Home remedy/herbal medicine           5             e
6  f8300                 None of the above           4             d

You can view the code on GitHub as well.

Leave a comment