简体   繁体   English

如何将数据框的一列的值转换为 0 和 1?

[英]How to convert the values of a column of a data frame to 0s and 1s?

I am working on a negative binomial regression model, which predicts the number of initiated private member bills by MPs in Japan based on their voteshare, age, sex and parliamentary office.我正在研究负二项式回归 model,它根据投票份额、年龄、性别和议会职位来预测日本国会议员发起的私人议员法案的数量。 In order to calculate the AME for the parliamentary_office variable I need to create two new data frames df.0 and df.1.为了计算议会办公室变量的 AME,我需要创建两个新的数据框 df.0 和 df.1。 As an example, here's the data frame df.0:例如,这里是数据框 df.0:

  (Intercept) voteshare age sexmale term parliamentary_office
1           1     37.92  57    male    0                    0
2           1     45.99  65    male    5                    0
3           1     36.18  59  female    3                    0
4           1      43.3  47    male    1                    0
5           1     45.48  58    male    5                    0
6           1     31.89  44    male    0                    0

How to convert the the sexmale column to numbers?如何将性别列转换为数字?

Here is my code:这是我的代码:

#rm(list=ls())
library(foreign)
dat <- read.dta(file = 'activity.dta', convert.factors = FALSE)
dat_clear <- na.omit(dat)
datc_2012 <- dat_clear[dat_clear$election == 2012, ]

library(MASS)
summary(m2.negbin <- glm.nb(num_pmbs_initiated ~
voteshare + age + sex + term
+ parliamentary_office, data = datc_2012,
link = "log"))

df.0 <- data.frame(cbind(1,
m2.negbin[["model"]]$voteshare,
m2.negbin[["model"]]$age,
m2.negbin[["model"]]$sex,
m2.negbin[["model"]]$term,
m2.negbin[["model"]]$parliamentary_office))

colnames(df.0) <- names(coef(m2.negbin))
df.1 <- df.0
df.0[,"parliamentary_office"] <- 0
df.1[,"parliamentary_office"] <- 1 

you can use the ifelse function if you only have only male and female and need to change the column into 0-1 numbers.如果您只有男性和女性并且需要将列更改为 0-1 数字,则可以使用 ifelse function。

df.0$sexmale <- sapply(df.0$sexmale, function (x) ifelse(x == "male", 0, 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM