R 在数据帧的特定位置放置特定值 DF

R 在数据帧的特定位置放置特定值 DF,r,R,以下是我将如何做到这一点。 首先,我将定义一个helper函数 DF <- data.frame(x1=c(NA,7,7,8,NA), x2=c(1,4,NA,NA,4)) # a data frame with NA WhereAreMissingValues <- which(is.na(DF), arr.ind=TRUE) # find the position of the missing values Modes <- apply(DF, 2,

以下是我将如何做到这一点。 首先,我将定义一个helper函数

    DF <- data.frame(x1=c(NA,7,7,8,NA), x2=c(1,4,NA,NA,4)) # a data frame with NA
    WhereAreMissingValues <- which(is.na(DF), arr.ind=TRUE) # find the position of the missing values
    Modes <- apply(DF, 2, function(x) {which(tabulate(x) == max(tabulate(x)))}) # find the modes of each column
DF
WhereAreMissingValues
Modes

Map
在这里提供了一种单线解决方案:

DF[] <- lapply(DF, function(x){x[is.na(x)] <- Myfunc(x) ; x})
DF
#   x1 x2
# 1  7  1
# 2  7  4
# 3  7  4
# 4  8  4
# 5  7  4

很好的回答,我学到了一些我不知道的东西,那就是map函数。非常感谢。这不完全是一行解决方案,因为您需要首先使用
apply
或使用
dplyr
来计算
Modes
模式,或者使用
dplyr
对每个模式进行变异(DF,funs(replace(,which.na(.),Myfunc(.))
@akrun,是的,我正在考虑使用
数据进行计算。table
DF[,lapply(.SD,function(x){[is.na(x)]@DavidArenburg
替换为
,在某些情况下,该选项在进行基准测试时会更快。这里没有进行基准测试。但无论如何,这是一个选项,并不意味着它会更好
DF[] <- lapply(DF, function(x){x[is.na(x)] <- Myfunc(x) ; x})
DF
#   x1 x2
# 1  7  1
# 2  7  4
# 3  7  4
# 4  8  4
# 5  7  4
data.frame(Map(function(u,v){u[is.na(u)]=v;u},DF, Modes))

#  x1 x2
#1  7  1
#2  7  4
#3  7  4
#4  8  4
#5  7  4