I've recently started using lapply and wanted to use it for another task. However in my new columns b and c the function of 'i' needs to use values from 'i-1' (I'm calling values from the row before basically)
The if statement is there to avoid calling g[0] when I=1 since this number does not exist. Is there a more elegant way to get rid of this if statement? ALSO, does not look like the code allows to use g[I-1]? Is there an easy work around? Thank you so much
o <- lapply(1:(nrow(Market)), function(i) {
a <- Market[i,3]
if (i == 1) {
b <- - Market[i,2] * Market[i,3]/(Market[i,3]+ Market[i,4])
c <- - Market[i,2]- Market[i,3]
} else {
b <- (g[i-1]*(1+Market[i,11])- Market[i,2]) * Market[i,3]/(Market[i,3]+ Market[i,4]))
c <- g[i-1]*(1+Market[i,11]) - Market[i,2] - f[i]
}
c(a,b,c)
})
Output <- as.data.frame(do.call(rbind, o))
Aucun commentaire:
Enregistrer un commentaire