在没有For循环的情况下替换或插入R中的NA值

Ric*_*ter 1 replace for-loop r na

有没有更好的方法在数据框中进行观察并估算NA值?我已经整理了一个似乎可以完成工作的'for循环',用行的平均值交换NAs,但我想知道是否有更好的方法不使用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 
Run Code Online (Sandbox Code Playgroud)

Dav*_*urg 5

这是一种可能的矢量化方法(没有任何循环)

indx <- which(is.na(df), arr.ind = TRUE)
df[indx] <- rowMeans(df, na.rm = TRUE)[indx[,"row"]]
Run Code Online (Sandbox Code Playgroud)

一些解释

我们可以NA使用arr.ind参数来识别s 的位置which.然后我们可以简单地索引df(通过行和列索引)和行意味着(仅通过行索引)并相应地替换值