R语言 使用密钥重新Map数据库

cgfeq70w  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(91)

我有一个数据集要使用key-dataset更新。我想将数据集中的条目(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))
ia2d9nvy

ia2d9nvy1#

一个选项是使用键/值对作为命名向量来匹配列

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>
rslzwgfq

rslzwgfq2#

另一种解决方案是使用match

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

相关问题