Extracting coefficient variable names from glmnet into a data.frame

后端 未结 8 1972
小鲜肉
小鲜肉 2020-12-05 00:09

I would like to extract the glmnet generated model coefficients and create a SQL query from them. The function coef(cv.glmnet.fit) yields a \'dgCMa

8条回答
  •  天命终不由人
    2020-12-05 00:53

    # requires tibble.
    tidy_coef <- function(x){
        coef(x) %>%
        matrix %>%   # Coerce from sparse matrix to regular matrix.
        data.frame %>%  # Then dataframes.
        rownames_to_column %>%  # Add rownames as explicit variables.
        setNames(c("term","estimate"))
    }
    

    Without tibble:

    tidy_coef2 <- function(x){
        x <- coef(x)
        data.frame(term=rownames(x),
                   estimate=matrix(x)[,1],
                   stringsAsFactors = FALSE)
    }
    

提交回复
热议问题