Reputation: 365
I am trying to aggregate certain columns of a data frame. In my data frame each column correponds to an industry and each row to a particular country. Idealy I would like to aggregate certain columns by weighted average. However for a small fraction the weights are missing. In this case I would like that R would aggregate for this country the industries by a simple average. A snipet from the data frame (these are exemplary weights for other columns)
| Mining | Food | weight85| weight90.93|
|:----------:|-- -----:|---------:|------------|
| 0.9608709| 0.8839236| 0.2738525| 0.1943577|
| 0.6445055| 0.8483874| 0.2958678| 0.1043844|
| 0.6977353| 0.9449249| NA| NA|
| 0.7970192| 0.5941056| 0.2324452| 0.1904089|
| 0.7261323| 0.6333187| NA| NA|
| 0.9959837| 1.0101725| 0.3872314| 0.1628354|
I compute the weighted average when ingoring the missing values problem as follows:
GGPC$mining.weighted <- GGPC$weight85*GGPC$Mining
GGPC$food.weighted <- (1-GGPC$weight85)*GGPC$food
GGPC$food.mining<- rowSums(GGPC[,54:55], na.rm=T)
Upvotes: 1
Views: 239
Reputation: 365
Building on the answer which mts provided. I came up with following solution for a solution, which computes for one row either the simple average or the weighted average.
if(sum(is.na(DF[1,37])>0)) {1/2*DF[1,5]+1/2*DF[1,6]}
else { DF[1,37]*GGPC[1,5]+(1-DF[1,37])*DF[1,6]}
And further looping through the rows of a data frame
DF$data.column.agg <- 0
for (i in 1:length(DF)) {
DF[i,*data.column.agg*] <- if(sum(is.na(DF[i,*weight column*])>0)) {*simple average* }
else {DF[i,*weight column*]*GGPC[i,*data column1*]+(1-DF[i,*weight column*])*GGPC[i,*data column2*]}
}
Upvotes: 0