は、ベクトルnum_var
は、データフレームの最初の列で開始しないと隣接していないんので、あなたのコメントによると、あなたはこの
# simple example with just four columns
allProspect.tst <- data.frame(one=c(1:3,8), two=c(NA,4:6), three=1:4, four= c(5,NA,7, 8))
# want to replace NAs in columns "two" and "four" with values 5 and 7, respectively
num_var <- c("two","four")
median.to.replace <- c(5, 7)
# let's see the data before replacement
print(allProspect.tst)
## one two three four
##1 1 NA 1 5
##2 2 4 2 NA
##3 3 5 3 7
##4 8 6 4 8
# just loop over the collection of column names (not indices)
for (name_col in num_var) {
na_rows <- is.na(allProspect.tst[,name_col])
# key is to get the corresponding element in median.to.replace
# using which() index in num_var has value equal name_col
allProspect.tst[na_rows,name_col] <- median.to.replace[which(num_var==name_col)]
}
# now let's see the replaced data
print(allProspect.tst)
## one two three four
##1 1 5 1 5
##2 2 4 2 7
##3 3 5 3 7
##4 8 6 4 8
アップデートが必要になります。それをより効率的に
多数の列に対して置換操作を効率化する方法はたくさんありますが、最も基本的なものは*apply
ファミリの関数look here for an excellent overview、R base
パッケージから入手可能である。次のように更新されたコードは次のとおり
replace.with.median <- function(col, median.val, df) {
na_rows <- is.na(df[, col])
df[na_rows, col] <- median.val
return(df[, col])
}
allProspect.tst[, num_var] <- mapply(replace.with.median, num_var, median.to.replace,
MoreArgs=list(df=allProspect.tst))
print(allProspect.tst)
## one two three four
##1 1 5 1 5
##2 2 4 2 7
##3 3 5 3 7
##4 8 6 4 8
注
原for
ループの本体は関数replace.with.median
中に封入されています。入力引数は、次のとおり
col
:median.to.replace
df
から対応する代替値:
データを含むデータフレーム
median.val
を交換するNA
Sを見つけるために、列名この関数はcol
列をdf
から返します。NA
をmedian.valに置き換えます。
上記のリンクに記載の使用mapply
、:あなたは、いくつかのデータ構造(例えばベクトル、リスト)があり、それぞれの第一の要素に関数を適用したいときのために
、および各2番目の要素など、
はここで、私たちはお互いに「ロックステップ」で二つのベクトルnum_var
とmedian.to.replace
上で機能replace.with.median
を適用したいです。さらに、データフレームallProspect.tst
〜replace.with.median
をMoreArgs
引数のmapply
で提供します。
mapply
から返されるものは、NA
が置き換えられた列ベクトルのコレクションです。 allProspect.tst
の対応する列をこれらと置き換えます。
これが役に立ちます。
ようこそStackOverflow。 [MCVE] –
を提供してください。 'seq_along'は、1から' length(num_var) 'までの整数ベクトルを生成します。 data.frame(ID変数など)の列をスキップしている場合、適切にインデックスを作成していません。 – lmo
はmedian.to.replace a vectorですか? – aichao