繁体   English   中英

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

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

我正在研究负二项式回归 model,它根据投票份额、年龄、性别和议会职位来预测日本国会议员发起的私人议员法案的数量。 为了计算议会办公室变量的 AME,我需要创建两个新的数据框 df.0 和 df.1。 例如,这里是数据框 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

如何将性别列转换为数字?

这是我的代码:

#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 

如果您只有男性和女性并且需要将列更改为 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