I have a dataframe:
maennlich <- structure(list(nummer = c(1817L, 2152L, 1819L, 1487L, 628L, 357L
), name = c("Abdallah", "Abdelaziz", "Abdul", "Abraham", "Absalom",
"Achim"), geschlecht = c("m", "m", "m", "m", "m", "m"), sprache = c("arabisch",
"arabisch", "arabisch", "hebräisch/aramäisch", "hebräisch/aramäisch",
"deutsch"), p1 = c(-1.8363636363636, -1.1046511627907, -2.0869565217391,
-2.0961538461538, -1.5180722891566, -1.7560975609756), p2 = c(0.64556962025316,
0.40350877192982, 0.016393442622951, 1.8275862068966, 1.0533333333333,
1.1739130434783), p3 = c(-1.1891891891892, -0.8375, -1.2857142857143,
0.020408163265306, -0.59016393442623, 0.30666666666667), p4 = c(-0.66666666666667,
-0.57894736842105, -0.18055555555556, -0.79032258064516, -0.59154929577465,
-0.18072289156627), p5 = c(0.80898876404494, 0.56, 1.1685393258427,
0.086206896551724, 0.20588235294118, 0.36781609195402), p6 = c(0.047619047619048,
0.25454545454545, -0.29885057471264, 0.092307692307692, 0.42045454545455,
-0.45121951219512), p7 = c(-1.0540540540541, -0.7, -1.2285714285714,
-0.13207547169811, 0, 0), p8 = c(1.1571428571429, 1, 0.98863636363636,
0.88, 0.75438596491228, 0.64), p9 = c(-2.3888888888889, -1.7692307692308,
-2.0588235294118, -2.1428571428571, -1.8620689655172, 0.16326530612245
), p10 = c(-0.74509803921569, -0.48888888888889, -0.96341463414634,
0.8, 0.3125, 0.06)), row.names = c(1L, 2L, 3L, 6L, 7L, 8L), class = "data.frame")
I want to calculate the weighted mean of columns “p5”, “p7”, and “p10” using these weights: c(-0.589, 0.893, 0.968)
.
The weighted mean for the first row seems to be:
weighted.mean(c(0.8089888, -1.0540541, -0.7450980), c(-0.589, 0.893, 0.968))
[1] -1.681619
I have found several solutions here on Stack Overflow, but those that I have tried return a different result. For example:
as.matrix(maennlich[, c("p5", "p7", "p10")]) %*% c(-0.589, 0.893, 0.968)
[,1]
1 -2.1390196
2 -1.4281844
3 -2.7179693
6 0.6056807
7 0.1812353
8 -0.1585637
Why do I not get the same result? What am I doing wrong?
(I want the result as a vector, not as a column of the dataframe.)