1

I have a data frame with a row of numbers and a row of letters. Let's call this the "decoder key." Each column in the decoder key represents a mapping between numbers and letters.

I also have a data frame with a column of codes comprised of numbers of varying digits. I want to create a new variable in this latter data frame that "translates" these codes from numbers to letters using the decoder key. In other words, I'll have the original number-based codes and then I'll have another column with the letters that correspond to that code.

I tried to implement this with a loop and dplyr::recode() but (a) I bet there's a better way to do this and (b) recode doesn't seem to work with the indexing. Any solutions? Below is a small reproducible example. In the real data, the alphas, numbers, and codes vectors are very large.

# Load packages
library(dplyr)

# Generate decoder
key <- data.frame(alphas = c("A","B","C"),
                  numbers = c("1","2","3"),
                  stringsAsFactors = FALSE)

# Generate codes from the possible values
# found in key$numbers
code_df <- data.frame(codes = c("2313","2","123","321"),
                    stringsAsFactors = FALSE)

# Add "decoded value" to the codes table by
# converting any number in a code into the letter
# found above the code in the key data.frame. Loop
# through each possible number requiring decoding
# in the decoder table and replace it with the letter
# above it
for(i in 1:ncol(key)){
  code_df$codes <- dplyr::recode(x = code_df$codes, key[2,i] = key[1,i])
  }

Note: this is different from the following posts because I need to recode the variable rather than join two variables and I also have large enough data where I cannot do this manually.

Changing value of data frame based on another data frame

r language: how to create new column in data frame based on another data frame?

In R, how do you classify values in one data frame based on ranges in another data frame?

socialscientist
  • 3,759
  • 5
  • 23
  • 58

0 Answers0