生成一个虚拟变量 [英] Generate a dummy-variable

查看:48
本文介绍了生成一个虚拟变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在R中生成以下伪变量:

I have trouble generating the following dummy-variables in R:

我正在分析年度时间序列数据(时间段1948-2009).我有两个问题:

I'm analyzing yearly time series data (time period 1948-2009). I have two questions:

  1. 如何为观察#10(即1957年)生成虚拟变量(值= 1957年为1,否则为零)?

  1. How do I generate a dummy variable for observation #10, i.e. for year 1957 (value = 1 at 1957 and zero otherwise)?

如何生成一个虚拟变量,该变量在1957年之前为零,并且从1957年开始一直到2009年取值为1?

How do I generate a dummy variable which is zero before 1957 and takes the value 1 from 1957 and onwards to 2009?

推荐答案

如果变量很多,另一个可以更好地工作的选项是factormodel.matrix.

Another option that can work better if you have many variables is factor and model.matrix.

> year.f = factor(year)
> dummies = model.matrix(~year.f)

这将包括一个拦截列(全为1),并且数据集中每一年的每一列都为一列,唯一的列是默认"或拦截值.

This will include an intercept column (all ones) and one column for each of the years in your data set except one, which will be the "default" or intercept value.

您可以通过与model.matrix中的contrasts.arg混淆来更改选择默认"的方式.

You can change how the "default" is chosen by messing with contrasts.arg in model.matrix.

此外,如果要省略截距,则只需删除第一列或在公式末尾添加+0.

Also, if you want to omit the intercept, you can just drop the first column or add +0 to the end of the formula.

希望这很有用.

这篇关于生成一个虚拟变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆