首页 > 解决方案 > 如何替换数据集中的缺失点?

问题描述

我想编写一个函数R来接收任何数据集作为输入,这样数据集就会有一些缺失点(NA)。现在我想使用函数来替换数据集中缺失点 ( ) 的mean一些数字/值。NA我在想的是这样的功能:

x<function(data,type=c("mean", lag=2))

实际上,它应该计算缺失点之后的两个数字和之前的两个数字的平均值(因为我认为lag2函数中)。例如,如果缺失点位于第 12 位,则该函数应计算第 10、11、13 和 14 位数字的平均值,并将结果替换为第 12 位的缺失点。在特定情况下,例如,如果缺失点在最后一个位置,并且我们后面没有两个数字,则该函数应该计算相应列的所有数据的平均值并替换缺失点。这里我举个例子来说明清楚。考虑以下数据集:

3  7 8 0  8  12 2
5  8 9 2  8  9  1
1  2 4 5  0  6  7
5  6 0 NA 3  9  10
7  2 3 6  11 14 2
4  8 7 4  5  3  NA

在上述数据集中,第一个NA应替换为数字的平均值25(前两个数据)64(后两个数据)(2+5+6+4)/4等于17/4。最后一个NA应该替换为最后一列的平均值,(2+1+7+10+2)/5等于22/5

我的问题是如何在上述函数中添加一些代码(ifif-else或其他循环)以形成一个完整的函数来满足上述解释。我应该强调我想使用apply函数族。

标签: rif-statementnapoint

解决方案


data.table请使用该库找到以下一种解决方案。

代表

  • 您的数据:
m1 <- "3  7 8 0  8  12 2
       5  8 9 2  8  9  1
       1  2 4 5  0  6  7
       5  6 0 NA 3  9  10
       7  2 3 6  11 14 2
       4  8 7 4  5  3  NA"

myData<- read.table(text=m1,h=F)
  • 函数代码replaceNA
library(data.table)

replaceNA <- function(data){
  
  setDT(data)
  
  # Create a data.table identifying rows and cols indexes of NA values in the data.table
  NA_DT <- as.data.table(which(is.na(data), arr.ind=TRUE))
  
  # Select row and column indexes of NAs that are not at the last row in the data.table
  NA_not_Last <- NA_DT[row < nrow(data)]
  
  # Select row and column indexes of NA that is at the last row in the data.table
  NA_Last <- NA_DT[row == nrow(data)]
  
  # Create a vector of column names where NA values are not at the last row in the data.table
  Cols_NA_not_Last <- colnames(data)[NA_not_Last[,col]]
  
  # Create a vector of column names where NA values are at the last row in the data.table
  Cols_NA_Last <- colnames(data)[NA_Last[,col]]
  
  # Replace NA values that are not at the last row in the data.table by the mean of the values located 
  # in the two previous lines and the two following lines of the line containing the NA value
  data[, (Cols_NA_not_Last) := lapply(.SD, function(x) replace(x, which(is.na(x)), mean(c(x[which(is.na(x))-2], x[which(is.na(x))-1], x[which(is.na(x))+1], x[which(is.na(x))+2]), na.rm = TRUE))), .SDcols = Cols_NA_not_Last][]
  
  # Replace NA values that are at the last row in the data.table by the mean of all the values in the column where the NA value is found 
  data[, (Cols_NA_Last) := lapply(.SD, function(x) replace(x, which(is.na(x)), mean(x, na.rm = TRUE))), .SDcols = Cols_NA_Last][]

  return(data)
}
  • 使用您的数据测试功能
replaceNA(myData)
#>    V1 V2 V3   V4 V5 V6   V7
#> 1:  3  7  8 0.00  8 12  2.0
#> 2:  5  8  9 2.00  8  9  1.0
#> 3:  1  2  4 5.00  0  6  7.0
#> 4:  5  6  0 4.25  3  9 10.0
#> 5:  7  2  3 6.00 11 14  2.0
#> 6:  4  8  7 4.00  5  3  4.4

reprex 包于 2021-11-08 创建(v2.0.1)


推荐阅读