簡體   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