In R, how does one create an xgb.DMatrix object from an R data frame?

  • $\begingroup$ Check the docs dear... And Welcome Aboard... $\endgroup$
    – Aditya
    Jun 23, 2018 at 19:38
  • $\begingroup$ I did read the PDF and did not understand some parts. I code example would be helpful. $\endgroup$ Jun 23, 2018 at 19:41
  • $\begingroup$ Checkout Kaggle R Kernels..., from the docs xgboost.readthedocs.io/en/latest/R-package/… $\endgroup$
    – Aditya
    Jun 23, 2018 at 19:42
  • $\begingroup$ I appreciate your attempt to help but the link you provided did not have a code example of relevance to my question. $\endgroup$ Jun 30, 2018 at 18:11
  • $\begingroup$ Just convert dataframe to matrix first using as.matrix() and then pass to xgb.Dmatrix() $\endgroup$
    – Aditya
    Jun 30, 2018 at 20:39

2 Answers 2


Welcome to the site!

Assume that y is your response, and x is your data set of predictors (where categorical variables have been appropriately converted to numeric). Your data does not necessarily need to be sparse, although sparse data will improve computation speed.

Then dtrain <- xgb.DMatrix(label = y, data = as.matrix(x)).

As you get more proficient with XGBoost you can start exploring the weight and base_margin parameters.


The short answer is that you can't do this directly. You have to start off with a sparse matrix or a libsvm file. See the discussion at https://goo.gl/kiHCqk for getting from a data frame to libsvm.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.