如何更改R中几个虚拟变量的值?

时间:2013-04-16 16:54:01

标签: r

我的数据框中有其他变量中有167个虚拟变量。为了创建用于预测的新数据,我希望将第一个虚拟变量的值更改为1,并将所有其他变量的值替换为零。我的虚拟变量称为district_code2,district_code3,district_code4等。所以我想修复district_code2取值1,所有其他值取值0.

我使用factor创建了这些虚拟变量,并使用model.matrix将它们添加到我的数据中 如在

 dummies = data.frame(model.matrix(~district_code, data=data_wht_81_09))
 #to get rid of the intercept
 dummies1<-dummies[,-1]

我需要在我的数据中使用假人,因为在我进行回归之后,我不希望在我的预测中考虑所有假人的系数。我想绘制相对于一个变量的拟合值,将所有其他变量保持为它们的平均值。对于区域虚拟对象,这意味着为所有拟合值添加常量。因此,我想将所有其他虚拟变量的值设置为0.可能有更有效的方法来执行此操作。我将显示对象虚拟对象的示例。

 dput(head(dummies1,4))
 structure(list(district_code2 = c(0, 0, 0, 0), district_code3 = c(0, 
 0, 0, 0), district_code4 = c(0, 0, 0, 0), district_code5 = c(0, 
 0, 0, 0), district_code6 = c(0, 0, 0, 0), district_code7 = c(0,0, 0, 0), 

我只显示前6个变量。我怎样才能做到这一点?非常感谢提前。

1 个答案:

答案 0 :(得分:1)

很少有人需要自己操作虚拟变量(当你使用因素时R会在幕后做这件事),但是,如果绝对需要,你可以简单地识别名称以discrict_code开头的列,以及更改其值:其他列将保持原样。

d <- data.frame( 
  district_code2 = c(0, 0, 0, 0), 
  district_code3 = c(0, 0, 0, 0), 
  district_code4 = c(0, 0, 0, 0), 
  district_code5 = c(0, 0, 0, 0), 
  district_code6 = c(0, 0, 0, 0), 
  district_code7 = c(0,0, 0, 0), 
  x = 1:4
)
library(stringr)
d[,str_detect(names(d), "^district_code[0-9]+")] <- 0
d[,1] <- 1
d