+5 votes
in Programming Languages by (71.8k points)

I trained a LASSO model using R library "glmnet". The training ran successfully. I wanted to create a dataframe using coefficients' name and their value. But the data.frame() function is throwing an error: R: cannot coerce class ‘structure("dgCMatrix", package = "Matrix")’ to a data.frame

How can I fix this error?

cv_model <- cv.glmnet(Xtr, ytr, alpha=1, parallel = TRUE, family = "gaussian", weights=weights)

best_lambda <- cv_model$lambda.min

model <- glmnet(Xtr, ytr, alpha = 1, lambda = best_lambda, family = "gaussian", weights=weights)

myCoefs <- coef(model)

fnames <- append(features.names, "None", 0) # since the first coef is intercept, add None at the start of the vector

myResults <- data.frame(features = myCoefs@Dimnames[[1]], 

featuresName = fnames, 

coefs = myCoefs)

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

It seems that the values you are trying to add to the dataframe are of class "structure".

You need to use indices to select elements from myCoefs@Dimnames[[1]].

Make the highlighted changes to your code and it should fix the error.

sze = length(myCoefs)
myResults <- data.frame(features = myCoefs@Dimnames[[1]][1:sze],
                        featuresName = fnames[1:sze],
                        coefs = myCoefs[1:sze])

Related questions

+5 votes
1 answer
+5 votes
1 answer
+2 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer

...