用一个函数从一个数据集中的NA值替换为另一个数据集中的值

17

我经常遇到这样的情况,需要从另一个聚合级别的数据帧中提取值来替换数据帧中缺失的值。例如,如果我有一个包含县级数据的数据帧,我可能会使用存储在另一个数据帧中的州级值来替换NA值。在多次编写 merge ... ifelse(is.na()) 等代码后,我决定编写一个函数来执行此操作。

这是我准备的函数和如何使用它的示例:

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日,我发现我的示例中存在逻辑错误,已进行修复。

3个回答

14

这是一个好问题。

以下是 data.table 的解决方案:

# Convert data.frames to data.tables (i.e. data.frames with extra powers;)
library(data.table)
fillDT <- data.table(fillDf, key=c("a", "b"))
naDT <- data.table(naDf, key=c("a", "b"))


# Merge data.tables, based on their keys (columns a & b)
outDT <- naDT[fillDT]    
#      a b  f  g f.1 g.1
# [1,] 1 3 NA  0 100  11
# [2,] 1 3 NA NA 100  11
# [3,] 1 3 NA  0 100  11
# [4,] 1 3  0  0 100  11
# [5,] 1 3  0 NA 100  11
# First 5 rows of 200 printed.

# In outDT[i, j], on the following two lines 
#   -- i is a Boolean vector indicating which rows will be operated on
#   -- j is an expression saying "(sub)assign from right column (e.g. f.1) to 
#        left column (e.g. f)
outDT[is.na(f), f:=f.1]
outDT[is.na(g), g:=g.1]

# Just keep the four columns ultimately needed   
outDT <- outDT[,list(a,b,g,f)]
#       a b  g   f
#  [1,] 1 3  0   0
#  [2,] 1 3 11   0
#  [3,] 1 3  0   0
#  [4,] 1 3 11   0
#  [5,] 1 3 11   0
# First 5 rows of 200 printed.

很好。一些评论可能会帮助我理解它。看起来很简洁! :) - JD Long
好的--我稍微加了一些注释。如果你有兴趣学习更多,?data.table 的“示例”部分是典范,值得花大约20分钟来仔细研究。特别是如果你是一个大数据专家--而且看起来你可能是--这个前期时间投资真的非常值得。 - Josh O'Brien
现在应该将此更改为 f:=i.fg:=i.g 吗? - rawr

6
这里是您的方法的稍微简洁/健壮版本。您可以用 lapply 调用替换for循环,但我觉得循环更容易阅读。
该函数假设除了mergeCols中的任何列都可以填充其NAs。我不确定这是否有帮助,但我愿意冒与选民打赌的险。
fillNaDf.ju <- function(naDf, fillDf, mergeCols) {
  mergedDf <- merge(fillDf, naDf, by=mergeCols, suffixes=c(".fill",""))
  dataCols <- setdiff(names(naDf),mergeCols)
  # loop over all columns we didn't merge by
  for(col in dataCols) {
    rows <- is.na(mergedDf[,col])
    # skip this column if it doesn't contain any NAs
    if(!any(rows)) next
    rows <- which(rows)
    # replace NAs with values from fillDf
    mergedDf[rows,col] <- mergedDf[rows,paste(col,"fill",sep=".")]
  }
  # don't return ".fill" columns
  mergedDf[,names(naDf)]
}

3
我更喜欢从合并中提取匹配代码,然后自己处理数据,以保持原始数据框的行列顺序不变。我还使用矩阵索引来避免任何循环,虽然为此我会创建一个带有修改过的fillCols的新数据框,并用它替换原始数据框的列;我认为我可以直接填充它,但显然你不能使用矩阵排序来替换数据框的部分内容,所以在某些情况下,通过列名进行循环可能会更快。
使用矩阵索引的方法如下:
fillNaDf <- function(naDf, fillDf, mergeCols, fillCols) {
  fillB <- do.call(paste, c(fillDf[, mergeCols, drop = FALSE], sep="\r"))
  naB <- do.call(paste, c(naDf[, mergeCols, drop = FALSE], sep="\r"))
  na.ind <- is.na(naDf[,fillCols])
  fill.ind <- cbind(match(naB, fillB)[row(na.ind)[na.ind]], col(na.ind)[na.ind])
  naX <- naDf[,fillCols]
  fillX <- fillDf[,fillCols]
  naX[na.ind] <- fillX[fill.ind]
  naDf[,colnames(naX)] <- naX
  naDf
}

使用循环:

fillNaDf2 <- function(naDf, fillDf, mergeCols, fillCols) {
  fillB <- do.call(paste, c(fillDf[, mergeCols, drop = FALSE], sep="\r"))
  naB <- do.call(paste, c(naDf[, mergeCols, drop = FALSE], sep="\r"))
  m <- match(naB, fillB)
  for(col in fillCols) {
    fix <- which(is.na(naDf[,col]))
    naDf[fix, col] <- fillDf[m[fix],col]
  }
  naDf
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接