首页 > 解决方案 > 从 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)

写出每种输入类型的因素似乎比我预期的要繁琐。清理它的最佳方法是什么?

标签: r

解决方案


您可以自动化所有这些。

for(cn in colnames(loan_data)) {
  new_loan_frame[,cn] <- factor(new_loan_frame[,cn], levels=levels(loan_data[,cn]))
}

推荐阅读