我有一个数据集要使用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))
2条答案
按热度按时间ia2d9nvy1#
一个选项是使用键/值对作为命名向量来匹配列
rslzwgfq2#
另一种解决方案是使用
match
: