【发布时间】:2015-11-05 15:34:23
【问题描述】:
是否有更好的方法来通过数据框中的观察并估算 NA 值?我已经组合了一个似乎可以完成工作的“for循环”,将NA与行的平均值交换,但我想知道是否有更好的方法不使用for循环来解决这个问题——也许内置的 R 函数?
# 1. Create data frame with some NA values.
rdata <- rbinom(30,5,prob=0.5)
rdata[rdata == 0] <- NA
mtx <- matrix(rdata, 3, 10)
df <- as.data.frame(mtx)
df2 <- df
# 2. Run for loop to replace NAs with that row's mean.
for(i in 1:3){ # for every row
x <- as.numeric(df[i,]) # subset/extract that row into a numeric vector
y <- is.na(x) # create logical vector of NAs
z <- !is.na(x) # create logical vector of non-NAs
result <- mean(x[z]) # get the mean value of the row
df2[i,y] <- result # replace NAs in that row
}
# 3. Show output with imputed row mean values.
print(df) # before
print(df2) # after
【问题讨论】:
-
当您提供带有随机数生成的数据时,您应该始终使用
set.seed -
@akrun,很好的发现。看来那里的答案和我的一模一样。哦,好吧,我猜伟大的思想是一样的:)
-
@akrun imo,这个问题并不相同...... OP 没有接受另一个问题的答案。 ;) 我确实认为它可以帮助其他人通过查看处理和提出相关问题的不同方式来学习,尤其是在 R 中。我相信,这个问题的答案解释和结构具有一定的价值。
-
好的,然后重新打开。