我经常遇到需要用来自不同聚合级别的其他 data.frame 的值替换 data.frame 中的缺失值的情况。因此,例如,如果我有一个充满县数据的 data.frame,我可能会将 NA 值替换为存储在另一个 data.frame 中的州值。在写了同样的merge
... ifelse(is.na())
yada yada 几十次之后,我决定分解并编写一个函数来做到这一点。
这是我制作的内容,以及我如何使用它的示例:
fillNaDf <- function(naDf, fillDf, mergeCols, fillCols){
mergedDf <- merge(naDf, fillDf, by=mergeCols)
for (col in fillCols){
colWithNas <- mergedDf[[paste(col, "x", sep=".")]]
colWithOutNas <- mergedDf[[paste(col, "y", sep=".")]]
k <- which( is.na( colWithNas ) )
colWithNas[k] <- colWithOutNas[k]
mergedDf[col] <- colWithNas
mergedDf[[paste(col, "x", sep=".")]] <- NULL
mergedDf[[paste(col, "y", sep=".")]] <- NULL
}
return(mergedDf)
}
## test case
fillDf <- data.frame(a = c(1,2,1,2), b = c(3,3,4,4) ,f = c(100,200, 300, 400), g = c(11, 12, 13, 14))
naDf <- data.frame( a = sample(c(1,2), 100, rep=TRUE), b = sample(c(3,4), 100, rep=TRUE), f = sample(c(0,NA), 100, rep=TRUE), g = sample(c(0,NA), 200, rep=TRUE) )
fillNaDf(naDf, fillDf, mergeCols=c("a","b"), fillCols=c("f","g") )
所以在我运行这个程序后,我有一种奇怪的感觉,有人可能在我之前解决了这个问题,并且以更优雅的方式解决了这个问题。这个问题有更好/更容易/更快的解决方案吗?另外,有没有办法消除我函数中间的循环?那个循环就在那里,因为我经常在不止一列中替换 NA。而且,是的,该函数假定我们要填充的列的名称相同,并且我们要填充的列同样适用于合并。
任何指导或重构都会有所帮助。
12 月 2 日编辑我意识到我的示例中有逻辑缺陷,我已修复。