r - 从 R 中的先前数据帧复制因子
问题描述
我想将因子级别从预先存在的数据框中复制到新创建的数据框中,而不是手动分配级别。
为了使用“预测”功能,R 要求新数据位于因子与模型训练数据相同的数据框中。我想相信这些因素可以从训练数据复制到新的数据框。我已经让它工作了,如下面的代码所示,虽然很笨拙。
# Build the model
naive_model <- NaiveBayes(outcome ~ purpose_ + home_ + emp_len_, data = loan_data, na.action = na.omit)
# Create new data point to be tested
new_loan_frame <- data.frame(purpose_ = "small_business", home_ = "MORTGAGE", emp_len_ = "> 1 Year")
# Add the necessary factors to match the training data
new_loan_frame$purpose_ <- factor(new_loan_frame$purpose_, levels = c("credit_card","debt_consolidation", "home_improvement", "major_purchase", "medical","other","small_business"))
new_loan_frame$home_ <- factor(new_loan_frame$home_, levels = c("MORTGAGE", "OWN", "RENT"))
new_loan_frame$emp_len_ <- factor(new_loan_frame$emp_len_, levels = c("< 1 Year", "> 1 Year"))
# Run the prediction using the model and the new data
predict(naive_model, new_loan_frame)
写出每种输入类型的因素似乎比我预期的要繁琐。清理它的最佳方法是什么?
解决方案
您可以自动化所有这些。
for(cn in colnames(loan_data)) {
new_loan_frame[,cn] <- factor(new_loan_frame[,cn], levels=levels(loan_data[,cn]))
}
推荐阅读
- c++ - 如何检查我打开的文件是否用于在 c 中读取或写入
- c# - 如何在 ASP.NET Core 3.1 MVC 中挂钩视图创建并更改模型和视图名称?
- javascript - 带有图像和圆形进度条的圆形按钮
- python - 未执行 Aurora 目标的 AWS Glue Pre 和 Post 操作
- vba - 使用 Outlook 阅读 RSS 项目。如果网页有“找不到页面”,想要删除项目
- angular - 如何将模板引用变量传递给子组件
- python - Pygame窗口底角的白色标签
- python - 创建具有唯一对象实例的 NumPy
- java - 无法构建 Spring Boot Admin Client
- javascript - 数据表的 json 问题