【发布时间】:2021-10-03 15:46:17
【问题描述】:
我正在尝试创建一个函数,用我使用 Mice 包创建的值填充数据框中的 NA。
我使用这个先前的答案来创建自己运行良好的代码:Use apply on a dataframe to fill in missing values from another dataframe
这是我的工作代码:
inds <- match(df_raw$id,miceoutput$id)
df_raw$PIDS_14 <- ifelse(is.na(df_raw$PIDS_14), miceoutput$PIDS_14[inds], df_raw$PIDS_14)
但是,当我尝试使用以下代码创建一个执行相同操作的函数时:
impute <- function(x) {
df_raw$x <- ifelse(is.na(df_raw$x) == TRUE, miceoutput$x[inds],df_raw$x)
}
运行时出现以下错误
impute(PIDS_14)
Error in `$<-.data.frame`(`*tmp*`, x, value = logical(0)) : replacement has 0 rows, data has
77
我不明白为什么它可以作为独立的代码行正常工作,但同样的事情在函数中不起作用。任何帮助表示赞赏。
【问题讨论】:
-
尝试使用
df_raw[[x]]而不是df_raw$x,并将变量名称作为带引号的字符串传递:impute("PIDS14")。当然还有miceoutput[[x]][inds]。 -
我运行了@stefan 建议的代码,它运行没有错误。但是,它实际上并没有改变数据框中的值。