我在矢量中有一个变量名列表,我希望将其传递给函数,从输出中获取这些数据帧,并在循环的下一次迭代中用作函数的参数。
standardized_funct= function(train,test, my_variable) {
#handle missing values
train$my_variable = ifelse(is.na(train$my_variable)==TRUE, 'MISSING',my_variable)
my_variable=eval(substitute(my_variable))
# handle missing values and set factors equivalent
test$my_variable = ifelse(is.na(test$my_variable)==TRUE, 'MISSING',my_variable)
test$my_variable = factor(test$my_variable, levels = base::unique(train$my_variable))
train$my_variable =
factor(train$my_variable)
output_factors = list(TRAIN = train, TEST = test)
return(output_factors)
}
# setup dummy data
rm(mtcars)
mtcars2 = rbind(mtcars,mtcars)
list_of_var = c("hp","mpg",'cyl')
for (each_variable in list_of_var){
outputdf = standardized_funct(train = mtcars, test = mtcars2, my_variable = each_variable
mtcars = outputdf$TRAIN
mtcars2 = outputdf$TEST
# should loop through each variable and run the function...that transforms the values to factor
}