gpt4 book ai didi

r - 将数据框的列相乘

转载 作者:行者123 更新时间:2023-12-01 07:20:15 25 4
gpt4 key购买 nike

我一直为此而挠头。我有两个数据框: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解决方案( example ),但我无法想出答案。

由此产生的 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

最佳答案

sweep()是你的 friend ,对于这个特定的例子。它依赖于 df 中的名称和 weights顺序正确,但可以安排。

> nams <- names(weights)
> df[, nams] <- sweep(df[, nams], 2, unlist(weights), "*")
> df
group age income assets
1 1 150 1000 500
2 2 200 3000 650
3 3 250 5000 800

如果变量名在 weightsdf顺序不同,您可以将它们设置为:
> df2 <- 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))
> nams <- c("age", "income") ## order in df2
> weights2 <- weights[, rev(nams)]
> weights2 ## wrong order compared to df2
income age
1 10 5
> df2[, nams] <- sweep(df2[, nams], 2, unlist(weights2[, nams]), "*")
> df2
group age income assets
1 1 150 1000 500
2 2 200 3000 650
3 3 250 5000 800

换句话说,我们重新排序所有对象,以便 ageincome顺序正确。

关于r - 将数据框的列相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13019003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com