简体   繁体   中英

How do I repeat a calculation on a column in R?

I'm stuck; I've been playing around with loops (I know, not a favorable option in R) and played a hand at the apply function on my query.

I have a column of data that is logging whether a day on the FTSE has been a gain or a loss. I want to sum the first 3 rows of the column that displays this and divide it by 3. I want to repeat this all the way through the nrow(DaysDifference) .

Please find a workable example below;

> FTSE[1:10,]
           FTSE.Open FTSE.High FTSE.Low FTSE.Close FTSE.Volume FTSE.Adjusted
2007-01-01    6220.8    6220.8   6220.8     6220.8           0        6220.8
2007-01-02    6220.8    6312.5   6220.8     6310.9  1074946500        6310.9
2007-01-03    6310.9    6322.0   6296.0     6319.0  1606892700        6319.0
2007-01-04    6319.0    6319.0   6261.0     6287.0  1902875600        6287.0
2007-01-05    6287.0    6287.0   6220.1     6220.1  1622439300        6220.1
2007-01-08    6220.1    6246.0   6187.0     6194.2  1326700900        6194.2
2007-01-09    6194.2    6218.5   6190.4     6196.1  2143699600        6196.1
2007-01-10    6196.1    6196.1   6142.0     6160.7  1881991200        6160.7
2007-01-11    6160.7    6233.1   6130.2     6230.1  2147062400        6230.1
2007-01-12    6230.1    6247.6   6204.3     6239.0  1899868200        6239.0

DaysDifference <- FTSE$FTSE.Open - FTSE$FTSE.Close
    colnames(DaysDifference) <- c('FTSE.Direction')

DaysDifference$PosInd<-ifelse(DaysDifference$FTSE.Direction>0,1,0)
# Identifys if D3P is > and if it is assigns 1, if not assigns 0

    DaysDifference$TestCol<- for (i in (nrow(DaysDifference)-3))
                {sum(DaysDifference$PosInd[i:(i+2)]/3)
                }

The above gives me a NULL result with the for DaysDifference$PosInd ... and then the ...

x <- apply(DaysDifference$PosInd, 1, function(i) sum(DaysDifference$PosId[i:(i+2)]/3))

trial does not iterate correctly over the vector and puts the same result as calculted on the first iteration of i:(i+2) .

Any help, as always, hugely appreciated.

Calvin

Have a look at the zoo package

library(zoo)
rollmean(DaysDifference$FTSE.Direction > 0, k = 3, na.pad = TRUE)

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