我有一個面板數據集,如下所示。但實際的數據集有幾千個觀測值。我想在1984 - 1998年(15年)內創建14個工廠作爲新的「Year_dum」欄。我搜索了在r中創建虛擬變量,但找不到使用年份整數的方法。任何人都可以幫我在r做這件事。在r中創建年份整數的因子變量
+--------+------+------+------+----------+ | Time | year | Firm | Prod | Year_dum | +--------+------+------+------+----------+ | Jan-84 | 1984 | A | 28.2 | 0 | | Feb-84 | 1984 | A | 26.6 | 0 | | Mar-84 | 1984 | A | 30.3 | 0 | | Apr-85 | 1985 | A | 33.2 | 1 | | May-85 | 1985 | A | 30.1 | 1 | | Jun-85 | 1985 | A | 28.3 | 1 | | Jan-84 | 1984 | B | 28.6 | 0 | | Feb-84 | 1984 | B | 28.9 | 0 | | Mar-84 | 1984 | B | 28.1 | 0 | | Oct-84 | 1984 | C | 28.8 | 0 | | Nov-85 | 1985 | C | 31.6 | 1 | | Dec-86 | 1986 | C | 26.9 | 2 | | Jan-89 | 1989 | C | 28.6 | 5 | | Feb-98 | 1998 | C | 29.6 | 14 | +--------+------+------+------+----------+
這個簡單的數據集可以使用下面的dput訪問。
structure(list(Time = structure(c(6L, 4L, 9L, 2L, 10L, 8L, 6L,
4L, 9L, 12L, 11L, 3L, 7L, 5L, 1L, 1L, 1L), .Label = c("", "Apr-85",
"Dec-86", "Feb-84", "Feb-98", "Jan-84", "Jan-89", "Jun-85", "Mar-84",
"May-85", "Nov-85", "Oct-84"), class = "factor"), year = c(1984L,
1984L, 1984L, 1985L, 1985L, 1985L, 1984L, 1984L, 1984L, 1984L,
1985L, 1986L, 1989L, 1998L, NA, NA, NA), Firm = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L
), .Label = c("", "A", "B", "C"), class = "factor"), Prod = c(28.2,
26.6, 30.3, 33.2, 30.1, 28.3, 28.6, 28.9, 28.1, 28.8, 31.6, 26.9,
28.6, 29.6, NA, NA, NA), Year_dum = c(0L, 0L, 0L, 1L, 1L, 1L,
0L, 0L, 0L, 0L, 1L, 2L, 5L, 14L, NA, NA, NA)), .Names = c("Time",
"year", "Firm", "Prod", "Year_dum"), class = "data.frame", row.names = c(NA,
-17L))
什麼是您預期的輸出? – akrun
我編輯了表格,以便它現在顯示我需要我的數據框中的年假人 – Doo
在下面發佈了一個解決方案 – akrun