【发布时间】:2022-01-07 12:14:58
【问题描述】:
我有两个数据框:一个(称为df_persons)的记录具有唯一的person_id,但具有不唯一的stratum_id,另一个(称为df_population)具有相同的记录stratum_id's,以及它们的多个重复行。在下面重新创建它们的代码:
df_persons = data.frame(person_id=c(101, 102, 103), stratum_id=c(1,2,1))
df_population = data.frame(stratum_id=c(1,1,1,1,2,2,2,2,3,3))
现在我想要一种将 df_persons 中的数据与 df_population 合并的方法,以便 df_persons 中的每一行都与 df_population 的第一个匹配 (key = stratum_id) 行合并,该行之前没有匹配过。在下面找到所需的解决方案:
# manual way to merge first available match
df_population$person = c(101, 103, NA, NA, 102, NA, NA, NA, NA, NA)
我为此编写了一个有效的循环(见下文)。问题是df_persons 有 83.000 条记录,df_population 有 1300 万条记录。因此循环需要太长时间 + 我的电脑无法处理它。
# create empty person column in df_population
df_population$person = NA
# order both df's to speed up
df_population = df_population[order(df_population$stratum_id),]
df_persons = df_persons[order(df_persons$stratum_id),]
# loop through all persons in df_person, and for each find the first available match
for(i_person in 1:nrow(df_persons))
{
match = F
i_pop = 0
while(!match)
{
i_pop = i_pop+1
if(df_population$stratum_id[i_pop] == df_persons$stratum_id[i_person] & is.na(df_population$person[i_pop]))
{
match = T
df_population$person[i_pop] = df_persons$person[i_person]
}
}
}
任何有助于加快此过程的帮助将不胜感激。我已经查看了 data.frame 包,但到目前为止无济于事,但我确实认为我需要摆脱循环才能执行代码。
【问题讨论】: