R:基于另一个数据帧

时间:2017-10-26 17:15:03

标签: r vectorization recode

我的数据框有一行数字和一行字母。我们称之为“解码器密钥”。解码器密钥中的每一列代表数字和字母之间的映射。

我还有一个数据框,其中一列代码由不同数字的数字组成。我想在后一个数据框中创建一个新变量,使用解码器密钥将这些代码从数字“转换”为字母。换句话说,我将拥有原始的基于数字的代码,然后我将拥有另一列,其中包含与该代码对应的字母。

我尝试使用循环和dplyr::recode()来实现它,但是(a)我打赌有更好的方法来执行此操作,并且(b)重新编码似乎不适用于索引。有解决方案吗以下是一个可重复的小例子。在实际数据中,alphasnumberscodes向量非常大。

# 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])
  }

注意:这与以下帖子不同,因为我需要重新编码变量而不是连接两个变量,而且我还有足够大的数据,我无法手动执行此操作。

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?

0 个答案:

没有答案
相关问题