CC Tan
CC Tan

Reputation: 23

Sum of each specific columns of total subset in R

I just started to learn R and I would like to use it in simulation of options pricing. I wrote a function to create 1000 data.frames as below. I'd like to get mean of "yBaseCcy" at each "Period" t, anyway to do this?

[[9]]
  Period ccyPairs        x    K     P        IV yBaseCcy yTermCcy LyBaseCcy
1      1   USDZAR 13.03787 12.8 0e+00 0.0000000     0.00      0.0         0
2      2   USDZAR 12.52903 12.8 1e+06 0.2709659 21627.04 270965.9         0

[[10]]
  Period ccyPairs        x    K     P        IV yBaseCcy yTermCcy LyBaseCcy
1      1   USDZAR 12.09013 12.8 0e+00 0.7098709        0        0         0
2      2   USDZAR 12.01183 12.8 1e+06 0.0000000        0        0         0

Upvotes: 2

Views: 125

Answers (1)

josliber
josliber

Reputation: 44340

If all data frames have identical structure (the same number of rows, where each row is for the same period), then you can extract the vector of interest from each one, add them all up, and divide by the total number:

Reduce("+", lapply(dat, function(x) x$yBaseCcy)) / length(dat)
# [1] 3 4

Sample data:

(dat <- list(data.frame(Period=1:2, yBaseCcy=1:2), data.frame(Period=1:2, yBaseCcy=3:4), data.frame(Period=1:2, yBaseCcy=5:6)))
# [[1]]
#   Period yBaseCcy
# 1      1        1
# 2      2        2
# 
# [[2]]
#   Period yBaseCcy
# 1      1        3
# 2      2        4
# 
# [[3]]
#   Period yBaseCcy
# 1      1        5
# 2      2        6

Upvotes: 2

Related Questions