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?

4
  • 2
    Seems like chartr is relevant here. Commented Oct 26, 2017 at 17:21
  • Wow, never knew this existed in base R! I'll give it a try shortly and post an answer. Commented Oct 26, 2017 at 17:41
  • 1
    You may find a suitable dupe among these Commented Oct 26, 2017 at 17:43
  • 1
    @Henrik Nice One! Commented Oct 26, 2017 at 18:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.