create a sparse matrix; given the indices of non-zero elements for creation of dummy variables of a categorical column of a large dataset

為{幸葍}努か 提交于 2019-12-02 05:58:18

Try this:

spmat<-Matrix(0,nrow = 210000 ,ncol = 500,sparse = T)
locs<-Matrix(data=c(mydata$Var_1,mydata$Var_2),byrow=F,ncol=2)
spmat[locs]=1

Why do you want a sparse matrix? For a dummy matrix you can also just use:

model.matrix(~ . + 0, data = df)

The 0 indicates no intercept and the . indicates that all categorical variables will be transformed. Be sure to set these variables as factors using as.factor() beforehand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!