使用键重新映射数据库

时间:2019-07-11 20:17:22

标签: r dplyr mapping lapply mapply

我有一个要使用键数据集更新的数据集。 我想将数据集(group_1:group_3)中的条目更改为其相应的值。

请记住,实际上,我的关键数据集有+ 25k条目,而寻求有效的解决方案就是我要走的路!感谢所有帮助。

玩具示例

df <- data.frame(state=rep("state_a"),
             candidate=c("a","b","c"),
             group_1= c("g_1","g_2","g_3"),
             group_2= c("g_4","g_5",NA),
             group_3= c("g_5",NA,NA))

key <- data.frame(group=c("g_1","g_2","g_3","g_4","g_5"),
              leader=c("l_1","l_2","l_3","l_4","l_4"))

结果:

df <- data.frame(state=rep("state_a"),
             candidate=c("a","b","c"),
             group_1= c("g_1","g_2","g_3"),
             group_2= c("g_4","g_5",NA),
             group_3= c("g_5",NA,NA))

附加请求: 我想使用df_2(与df相同的维度)来确定保留df_final的条目,然后进行转换。

df_2 <- data.frame(state=rep("state_a"),
                   candidate=c("a","b","c"),
                   value_1= c("1","2","0"),
                   value_2= c("3","2",NA),
                   value_3= c("5",NA,NA))

df_final_temp <- data.frame(state=rep("state_a"),
             candidate=c("a","b","c"),
             group_1= c("g_1","g_2",NA),
             group_2= c("g_4","g_5",NA),
             group_3= c("g_5",NA,NA))

df_final <- data.frame(state=rep("state_a"),
             candidate=c("a","b","c"),
             group_1= c("l_1","l_2",NA),
             group_2= c("l_4","l_5",NA),
             group_3= c("l_5",NA,NA))

2 个答案:

答案 0 :(得分:1)

一种选择是将键/值对用作命名向量以匹配列

df[-(1:2)] <- setNames(as.character(key$leader), key$group)[as.matrix(df[-(1:2)])]    


df
#    state candidate group_1 group_2 group_3
#1 state_a         a     l_1     l_4     l_4
#2 state_a         b     l_2     l_4    <NA>
#3 state_a         c     l_3    <NA>    <NA>

答案 1 :(得分:1)

另一种解决方案是使用match

df[-(1:2)] <- as.data.frame(lapply(df[-(1:2)], function(x) key[match(x, key$group),2]))