我一直在为此挠头。我有两个数据框: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))
和weights
weights <- data.frame(age = 5, income = 10)
我只想将这两个数据框乘以相同的列名。我试过这样的事情:
colwise(function(x) {x * weights[names(x)]})(df)
但这显然不起作用,因为colwise
没有将列名保留在函数内。我查看了各种mapply
解决方案(示例),但无法找到答案。
结果data.frame
应如下所示:
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