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

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

问题描述

我在 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)

这将包括一个截距列(所有年份)和数据集中每一年的一列,除了一列,这将是默认"或截取值.

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天全站免登陆