'Getting variables names from glmnet lasso into a data.frame
I'm working with a phyloseq object ps.scale and trying to get the most important variables/features that can predict health status sample_data(ps.scale)$group.
Code is as follows:
library(glmnet)
metadata <- factor(sample_data(ps.scale)$group)
otu_tab <- otu_table(ps.scale)
otu_tab <- apply(otu_tab, 2, function(x) x+1/sum(x+1))
otu_tab <- t(log10(otu_tab))
y <- metadata
x <- otu_tab
lasso <- cv.glmnet(x, y, family="multinomial", alpha=1)
print(lasso)
plot(lasso)
So I get the results and a plot here.
#Call: cv.glmnet(x = x, y = y, family = "multinomial", alpha = 1)
#Measure: Multinomial Deviance
# Lambda Index Measure SE Nonzero
#min 0.03473 36 1.704 0.05392 68
#1se 0.05529 26 1.751 0.05474 16
Now I want to be able to extract the important variables/features (i.e., OTUs). Below are some codes I gathered from the internet:
Code 1
all_1se <- coef(lasso, s = "lambda.1se")
chosen_1se <- all_1se[all_1se > 0, ]
chosen_1se
#Error: 'list' object cannot be coerced to type 'double'
Code 2
tmp_coeffs <- coef(lasso, s = "lambda.1se")
data.frame(name = tmp_coeffs@Dimnames[[1]][tmp_coeffs@i + 1], coefficient = tmp_coeffs@x)
#Error in data.frame(name = tmp_coeffs@Dimnames[[1]][tmp_coeffs@i + 1], :
# trying to get slot "Dimnames" from an object of a basic class ("list") with no slots
Code 3
myCoefs <- coef(lasso, s="lambda.min");
myCoefs[which(myCoefs != 0 ) ]
myCoefs@Dimnames[[1]][which(myCoefs != 0 ) ] #feature names: intercept included
## Asseble into a data.frame
myResults <- data.frame(
features = myCoefs@Dimnames[[1]][ which(myCoefs != 0 ) ], #intercept included
coefs = myCoefs [ which(myCoefs != 0 ) ] #intercept included
)
myResults
#Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'which': 'list' object cannot be coerced to type 'double'
#3.h(simpleError(msg, call))
#2..handleSimpleError(function (cond)
# .Internal(C_tryCatchHelper(addr, 1L, cond)), "'list' object cannot be coerced to type 'double'",
# base::quote(which(myCoefs != 0)))
#1.which(myCoefs != 0)
I need help fixing the above errors, mainly 'list' object cannot be coerced to type 'double'.
Thank you in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
