[英]recoding time series data in r
我正在嘗試使用超時結構來重新編碼現有數據。 我的數據集如下所示:
dput(z)
structure(list(democracy = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), year.x = 1967:2008, time = c(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42)), .Names = c("democracy", "year.x", "time"), row.names = 176:217, class = "data.frame")
因此,我想創建一個新的變量,例如time.democ,如果democracy==0
,則取值為零,但如果從democracy ==1
,則從1開始,直到democracy==0
,然后重新開始計算時間段。再次。 我將在一系列國家/地區進行此操作,但是我假設一旦正確使用此功能,使用ddply進行泛化就足夠容易了。 有什么建議么?
我想得到這個:
dput(z)
structure(list(democracy = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), year.x = 1967:2008, time = c(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42), new.time = c(0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0,
0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25)), .Names = c("democracy",
"year.x", "time", "new.time"), row.names = 176:217, class = "data.frame")
謝謝!
您可以結合使用rle
和sequence
來執行此操作。 rle
執行游程長度編碼,而sequence
生成序列。
z$new.time <- sequence(rle(z$democracy)$lengths)
z$new.time[z$democracy==0] <- 0
head(z, 20)
democracy year.x time new.time
176 0 1967 1 0
177 0 1968 2 0
178 0 1969 3 0
179 0 1970 4 0
180 0 1971 5 0
181 0 1972 6 0
182 1 1973 7 1
183 1 1974 8 2
184 1 1975 9 3
185 0 1976 10 0
186 0 1977 11 0
187 0 1978 12 0
188 0 1979 13 0
189 0 1980 14 0
190 0 1981 15 0
191 0 1982 16 0
192 1 1983 17 1
193 1 1984 18 2
194 1 1985 19 3
195 1 1986 20 4
多謝您的回覆。 我遵循了您的建議,最后編寫了一個函數,以便可以通過ddply將其應用於我的(縱向)數據集中的所有單元。 我發布它是因為它可能會幫助其他人,盡管我確信還有更優雅的解決方案:
# is a long format data frame
new.time <- function(a){
a <- a[order(a$year.x),]
a$new.time <- sequence(rle(a$democracy)$lengths)-1
a$new.time[a$democracy==0] <- 0
return(a)
}
merged1 <- ddply(merged, .(country.x), new.time)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.