生成一个虚拟变量

生成一个虚拟变量

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

我正在分析年度时间序列数据(时间周期1948至2009年)。我有两个问题:

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

  2. 如何生成一个虚拟变量,该变量在1957年之前为零,从1957年到2009年取值1?


慕仙森
浏览 861回答 3
3回答

牛魔王的故事

生成这些虚拟变量的最简单方法如下所示:> print(year)[1] 1956 1957 1957 1958 1958 1959> dummy <- as.numeric(year == 1957)> print(dummy)[1] 0 1 1 0 0 0> dummy2 <- as.numeric(year >= 1957)> print(dummy2)[1] 0 1 1 1 1 1更广泛地说,您可以使用ifelse根据条件在两个值之间进行选择。因此,如果由于某种原因,例如,4和7,而不是0-1虚拟变量,您可以使用ifelse(year == 1957, 4, 7).

倚天杖

使用假人:DUMIY():library(dummies)# example datadf1 <- data.frame(id = 1:4, year = 1991:1994)df1 <- cbind(df1, dummy(df1$year, sep = "_"))df1#&nbsp; &nbsp;id year df1_1991 df1_1992 df1_1993 df1_1994# 1&nbsp; 1 1991&nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 0# 2&nbsp; 2 1992&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 0# 3&nbsp; 3 1993&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp; 0# 4&nbsp; 4 1994&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; 1
打开App,查看更多内容
随时随地看视频慕课网APP