簡體   English   中英

從R中的先前數據幀復制因子

[英]Copying factors from previous data frames in 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]))
}

嗨,歡迎來到Stackoverflow。正確的是,為了進行預測,您必須在一個數據框中很好地組織數據。 請嘗試以下方法:

new_loan_frame <- data.frame(purpose= rep(levels(loan_data$purpose),3), home = rep(levels(loan_data$home),each=7), emp_len=rep(levels(loan_data$emp_len)))

Preds1<-predict(naive_model , newdata=new_load_frame, level=0)

另外,嘗試不要在級別名稱中使用“ _”。 相反,您可以簡單地使用: , sep="_")

祝好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM