Vera  Lee
Vera Lee

Reputation: 29

for loop to calculate returns for each column in R

I have prices saved in a matrix of 7 rows (7 months) and 8 columns (8 cities). I want to use a for loop to calculate the geometric mean returns for each column.

     [,1]  [,2]  [,3]  [,4]  [,5] [,6] [,7] [,8]
[1,] 22940 25206 35206 52104 63716 5992 7228 7005
[2,] 22019 25271 35160 52549 67951 5953 7172 6869
[3,] 21743 25730 35138 53087 66165 6061 7245 6846
[4,] 20941 25549 35291 55779 66428 6319 7315 6953
[5,] 20786 25500 36221 58128 66250 6562 7196 6990
[6,] 21177 25812 36735 60738 63204 6783 7155 6968
[7,] 20684 25911 37354 63716 62389 6942 7194 6923

I have the code as follows:

for (i in 1 : 8) {
policyPricesReturns[i] <- 1 + diff(log(policyPrices[,i]))[-1]
meanPolicyPricesReturns[i] <- geoMean(policyPricesReturns[i])
print(meanPolicyPricesReturns[i])
}

But it doesn't work, R shows me that "object 'policyPricesReturns" are not found. Could you help me with this? Many many thanks!!

Upvotes: 1

Views: 376

Answers (2)

konvas
konvas

Reputation: 14346

You probably want to use @ANG's suggestion (if your matrix only contains positive numbers), but if you're looking for a base R solution you can calculate it directly as

(-1) ^ colSums(policyPricesReturns < 0) * exp(colMeans(log(abs(policyPricesReturns))))

If you know that policyPricesReturns is always positive, use simply

exp(colMeans(log(policyPricesReturns)))

No need for a loop here as these functions operate on the whole matrix.

Upvotes: 1

nghauran
nghauran

Reputation: 6768

geometric.mean() from psych can be useful here. Try:

library(psych)
geometric.mean(mat)
# output
       V1        V2        V3        V4        V5        V6        V7        V8 
21456.963 25567.233 35862.503 56437.768 65129.888  6362.601  7214.829  6936.061

# data
mat <- structure(c(22940L, 22019L, 21743L, 20941L, 20786L, 21177L, 20684L, 
25206L, 25271L, 25730L, 25549L, 25500L, 25812L, 25911L, 35206L, 
35160L, 35138L, 35291L, 36221L, 36735L, 37354L, 52104L, 52549L, 
53087L, 55779L, 58128L, 60738L, 63716L, 63716L, 67951L, 66165L, 
66428L, 66250L, 63204L, 62389L, 5992L, 5953L, 6061L, 6319L, 6562L, 
6783L, 6942L, 7228L, 7172L, 7245L, 7315L, 7196L, 7155L, 7194L, 
7005L, 6869L, 6846L, 6953L, 6990L, 6968L, 6923L), .Dim = 7:8, .Dimnames = list(
    NULL, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8")))

Upvotes: 2

Related Questions