I have been scratching my head over this. I have two data frames: df
df <- data.frame(group = 1:3,
age = seq(30, 50, length.out = 3),
income = seq(100, 500, length.out = 3),
assets = seq(500, 800, length.out = 3))
and weights
weights <- data.frame(age = 5, income = 10)
I would like to multiply these two data frames only for the same column names. I tried something like this:
colwise(function(x) {x * weights[names(x)]})(df)
but that obviously didn’t work as colwise does not keep the column name inside the function. I looked at various mapply solutions (example), but I am unable to come up with an answer.
The resulting data.frame should look like this:
structure(list(group = 1:3, age = c(150, 200, 250), income = c(1000,
3000, 5000), assets = c(500, 650, 800)), .Names = c("group",
"age", "income", "assets"), row.names = c(NA, -3L), class = "data.frame")
group age income assets
1 1 150 1000 500
2 2 200 3000 650
3 3 250 5000 800
sweep()is your friend here, for this particular example. It relies upon the names indfandweightsbeing in the right order, but that can be arranged.If the variable names in
weightsanddfare not in the same order, you can make them so:In other words we reorder all objects so that
ageandincomeare in the right order.