年龄 工作 FNLWGT 教育 教育数字 婚姻状况 职业 关系 种族 性别 资本收益 资本损失 每周小时数 原产国 income 39 State-gov 77516 Bachelors 13 Never-married Adm-clerical Not-in-family White Male 2174 0 40 United-States <=50K 50 Self-emp-not-inc 83311 Bachelors 13 Married-civ-spouse Exec-managerial Husband White Male 0 0 13 United-States <=50K 38 Private 215646 HS-grad 9 Divorced Handlers-cleaners Not-in-family White Male 0 0 40 United-States <=50K 53 Private 234721 11th 7 Married-civ-spouse Handlers-cleaners Husband Black Male 0 0 40 United-States <=50K 28 Private 338409 Bachelors 13 Married-civ-spouse Prof-specialty Wife Black Female 0 0 40 Cuba <=50K 37 Private 284582 Masters 14 Married-civ-spouse Exec-managerial Wife White Female 0 0 40 United-States <=50K 49 Private 160187 9th 5 Married-spouse-absent Other-service Not-in-family Black Female 0 0 16 Jamaica <=50K 52 Self-emp-not-inc 209642 HS-grad 9 Married-civ-spouse Exec-managerial Husband White Male 0 0 45 United-States >50K 31 Private 45781 Masters 14 Never-married Prof-specialty Not-in-family White Female 14084 0 50 United-States >50K 42 Private 159449 Bachelors 13 Married-civ-spouse Exec-managerial Husband White Male 5178 0 40 United-States >50K,利用上述数据集,用R语言建立Logistic模型并对income是否高于50K做影响因素分析
时间: 2023-07-08 07:29:43 浏览: 51
以下是使用R语言建立Logistic模型并进行影响因素分析的示例代码:
```R
# 导入数据
data <- read.csv("adult.csv", header = FALSE)
# 添加列名
colnames(data) <- c("age", "workclass", "fnlwgt", "education", "education-num",
"marital-status", "occupation", "relationship", "race",
"sex", "capital-gain", "capital-loss", "hours-per-week",
"native-country", "income")
# 转换income为二元变量
data$income <- ifelse(data$income == ">50K", 1, 0)
# 删除无用变量
data <- data[, -c(3, 5, 9, 13)]
# 将分类变量转为虚拟变量
data <- data.frame(model.matrix(~ . - 1, data))
# 划分训练集和测试集
set.seed(123)
train_idx <- sample(1:nrow(data), size = nrow(data) * 0.7)
train_data <- data[train_idx, ]
test_data <- data[-train_idx, ]
# 建立Logistic模型
model <- glm(income ~ ., data = train_data, family = binomial)
# 查看模型结果
summary(model)
# 进行预测
pred <- predict(model, newdata = test_data, type = "response")
pred_class <- ifelse(pred > 0.5, 1, 0)
# 计算预测准确率
accuracy <- sum(pred_class == test_data$income) / nrow(test_data)
accuracy
```
在上面的代码中,我们首先导入数据,并添加列名。然后,我们将income变量转换为二元变量,并删除一些无用变量。接着,我们将所有分类变量转换为虚拟变量,并将数据集划分为训练集和测试集。然后,我们使用glm函数建立Logistic模型,并使用summary函数查看模型结果。最后,我们使用新数据进行预测,并计算预测准确率。