r - 如何替换数据集中的缺失点?
问题描述
我想编写一个函数R
来接收任何数据集作为输入,这样数据集就会有一些缺失点(NA
)。现在我想使用函数来替换数据集中缺失点 ( ) 的mean
一些数字/值。NA
我在想的是这样的功能:
x<function(data,type=c("mean", lag=2))
实际上,它应该计算缺失点之后的两个数字和之前的两个数字的平均值(因为我认为lag
在2
函数中)。例如,如果缺失点位于第 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
应替换为数字的平均值2
,5
(前两个数据)6
和4
(后两个数据)(2+5+6+4)/4
等于17/4
。最后一个NA
应该替换为最后一列的平均值,(2+1+7+10+2)/5
等于22/5
。
我的问题是如何在上述函数中添加一些代码(if
、if-else
或其他循环)以形成一个完整的函数来满足上述解释。我应该强调我想使用apply
函数族。
解决方案
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)
推荐阅读
- assets - redmine plugin_assets 仍然为空
- jupyter-notebook - 在 jupyter 笔记本树中看不到隐藏文件夹
- c# - 从 4.6.1 项目引用 .net framework 4.7.2 程序集
- javascript - 在数组中添加时间值
- php - 如果我没有/不能使用 DI 注入服务,我如何直接从容器中获取服务?
- java - 是否可以在 Thrift 结构中定义联合、嵌套结构和容器的默认值?
- python - Pytorch、Keras 风格的多个输出
- c# - C# DataTable 更新字符串列,格式为 exeption
- javascript - $(document).keydown/up 在使用辅助键时不起作用
- notepad++ - 如何添加用户定义语言的功能和相关描述?