多个 Replace/Lookups

Multiple Replace/Lookups

我有以下数据:

data_1 = data.frame(var1 = c("A", "B", "C"), var2 = c("A1", "A2", "A3"))
data_1$var1 = as.factor(data_1$var1)
data_1$var2 = as.factor(data_1$var2)

  var1 var2
1    A   A1
2    B   A2
3    C   A3

然后我有这个查找 Table:

lookup = data.frame(var_1_value = c("A", "B", "C"), var_1_code = c(1,2,3), var_2_value = c("A1", "A2", "A3"), var_2_code = c(4,5,6))

  var_1_value var_1_code var_2_value var_2_code
1           A          1          A1          4
2           B          2          A2          5
3           C          3          A3          6

我想用查找 Table 中的“代码”替换“data_1”中的值。我试着用这个问题作为灵感 ():

lookup1 <- setNames(as.character(lookup$var_1_code), lookup$var_1_value)
res <- data.frame(lapply(data_1, function(i) lookup1[i]))
rownames(res) <- NULL

但这并没有给出预期的输出:

> res
  var1 var2
1    1    1
2    2    2
3    3    3

我想这可能是因为我在之前的代码中从未提到过“var2”,但这也没有用:

lookup1 <- setNames(as.character(lookup$var_1_code), lookup$var_1_value, as.character(lookup$var_2_code), lookup$var_2_value)
res <- data.frame(lapply(data_1, function(i) lookup1[i]))
rownames(res) <- NULL

Error in setNames(as.character(lookup$var_1_code), lookup$var_1_value,  : 
  unused arguments (as.character(lookup$var_2_code), lookup$var_2_value)

预期输出应如下所示:

> res
  var1 var2
1    1    4
2    2    5
3    3    6

谢谢!

您可以使用 sapply:

res <- data.frame(
  sapply(
    seq_along(data_1), 
    function(i) lookup[match(data_1[, i], lookup[, 2 * i - 1]), 2 * i]
    )
  )

colnames(res) <- colnames(data_1)

结果 res 看起来像

  var1 var2
1    1    4
2    2    5
3    3    6