简易Lasso回归 R语言 变量含有分类变量处理
作者:互联网
#这是个简易的lasso, 里面有几个参数,像family,应该自主 ??函数 去调一下
#加载包
library(haven)
#导入数据
R <- read_dta("C:/Users/XXX/Desktop/R_cat.dta")
data <- R
#X变量都是连续变量
x <- as.matrix(data[,1:29])
y <- data[,30] #第30列是Y变量
x <- data.matrix(x)
y <- data.matrix(y)
alpha1_fit <- glmnet(x,y,alpha=1,family="binomial") #??glmnet看下family可以选择的
plot(alpha1_fit,xvar="lambda",label=TRUE)
alpha1.fit <- cv.glmnet(x,y,type.measure = "auc",alpha=1,family="binomial")
plot(alpha1.fit)
print(alpha1.fit)
coef(alpha1_fit,s=alpha1.fit$lambda.1se)
#如果X为分类变量
library(haven)
R <- read_dta("C:/Users/xxx/Desktop/lasso2.dta")
data <- R
#如果X为分类变量
xfactors <- model.matrix(group ~ agegroup+bmifz+occupation+
brush_rate+denture+hypertention+diabetes
,data=R)[,-1]
x <- as.matrix(data.frame(xfactors))
y <- data[,22]
y <- data.matrix(y)
library(glmnet)
alpha1_fit <- glmnet(x,y,alpha=1,family="binomial")
plot(alpha1_fit,xvar="lambda",label=TRUE)
set.seed(12345)
alpha1.fit <- cv.glmnet(x,y,type.measure = "auc",alpha=1,family="binomial")
plot(alpha1.fit)
print(alpha1.fit)
coef(alpha1_fit,s=alpha1.fit$lambda.1se)
标签:plot,alpha1,变量,fit,library,简易,data,Lasso 来源: https://blog.csdn.net/weixin_46623488/article/details/119490693