简体   繁体   中英

In R- for Loop Subsetting

I'm trying to teach myself R and am having a really hard time with loops. I've got the following dataset which extends down to 2008:

"","year","bdeadbes"
"1",1946,295541
"2",1947,396708
"3",1948,472363
"4",1949,434321
"5",1950,546501
"6",1951,393740

I'm trying to figure out how create a loop to subset for years 1951-2008, where for each iteration of the loop, the mean of the last 5 years is calculated and then stored in a new vector. So far, all I've been able to figure out is setting up the storage vector itself:

storage_vec<-rep(length(bd$year[1951:2008]))

I assume that the loop shell should be: for (i in 1:storage_vec){}

but I can't at all figure out how to properly subset the data for my desired operation. Can anyone point me in the right direction?

There are of course more efficient ways of doing this, but using a loop this is one option. The first value is just 393740 because there are no previous values to average with.

dtf <- read.csv(text="
    year,bdeadbes
    1946,295541
    1947,396708
    1948,472363
    1949,434321
    1950,546501
    1951,393740", header=TRUE)

dtf

v <- seq_along(dtf$year)

for (i in length(dtf$year):1) {
    v[i] <- mean(dtf$bdeadbes[(i:(i-5))+5], na.rm=TRUE)
}

rev(v)
# 393740.0 470120.5 458187.3 461731.2 448726.6 423195.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM