Calculate Gini coefficient by hand

I have been asked to calculate the Gini coefficient (dispersion of allocation weighting) in 18 sectoral ETFs with historical data available since 2000. Here is an excerpt:

> head(df)
Date  .SXQR  .SXTR  .SXNR  .SXMR  .SXAR  .SX3R  .SX6R  .SXFR  .SXOR  .SXDR
1 2000-01-03 364.94 223.93 489.04 586.38 306.56 246.81 385.36 403.82 283.78 455.39
2 2000-01-04 345.04 218.90 474.05 566.15 301.13 239.24 374.64 390.41 275.93 434.92
3 2000-01-05 338.22 215.88 464.20 542.29 298.22 239.55 373.26 383.48 272.54 430.05
4 2000-01-06 343.13 218.18 470.82 529.33 300.69 249.75 377.26 383.48 272.47 434.15
5 2000-01-07 349.46 220.10 478.87 531.65 306.50 255.17 381.19 390.23 273.76 447.02
6 2000-01-10 356.20 223.01 484.07 581.82 310.84 252.75 387.74 393.75 278.76 453.80


If you know an easier way to do it than my attempt I would be happy to hear it !

My attempt

I know that the index G is equal to Where E is the average of all the deviations in absolute value for all the pairs of the statistical variable studied: And M is the average income: Yet, while computing the mean of the portfolio_monthly_returns, M I have this error: argument is not numeric or logical: returning NA.

From a friend's idea I create portfolio_monthly_returns with :

library(quantmod)
portfolio_monthly_returns=lapply(xts(df[,-1],order.by = df\$Date),monthlyReturn) # What is monthlyReturn here ?


I don't get this code and it looks weird indeed: > mean(portfolio_monthly_returns)
 NA
Warning message:
In mean.default(portfolio_monthly_returns) :
argument is not numeric or logical: returning NA


Data

The data file is here.

In order to get df:

library (dplyr)
library (lubridate)

df <- read.xlsx ("Data.xlsx", sheet = "Sector-STOXX600", startRow = 2, colNames = TRUE, detectDates = TRUE, skipEmptyRows = FALSE)
df [2:19] <- data.matrix (df [2:19])


Remark

I don't know why it doesn't involve the weights:

cov = cor(NewData)
# ERC algorithm
Sigma = cov
w = optimalPortfolio(Sigma = Sigma,control = list(type = 'erc', constraint = 'lo'))

w = matrix(w, 1, 18)
(Sigma %*% t(w)) * c(w)