我有一个数据格式(DF1),列有:国家、年份、指标1、指标2、。等。
我有另一个带有列的dataframe (DF2):指示器、权重
现在,我希望将DF1的每个指示符乘以DF2权重列中的值。
例如,如果在DF2中,指标1的权重= 0.5,指标2的权重=0.2,而在DF1中,指标1的Country=Brazil,Year=2015,指标1= 0.34,指标2= 0.76。
我想得到这样的数据:
Country=Brazil、Year=2015、指标1=0.34x0.5、指标2=0.76x0.2等
x=乘积
我非常感谢任何帮助!)
发布于 2021-06-22 16:27:36
我们还可以使用deframe创建一个命名向量
library(dplyr)
library(tibble)
df %>%
mutate(across(starts_with('indicator'),
~ deframe(df_indicators)[cur_column()] * .))-output
country year indicator_1 indicator_2 indicator_3
1 ABC 1 10 39 36
2 BCD 1 24 30 28
3 ABC 2 16 18 16
4 BCD 2 14 15 32
5 CDE 3 12 24 48数据
df <- structure(list(country = c("ABC", "BCD", "ABC", "BCD", "CDE"),
year = c(1L, 1L, 2L, 2L, 3L), indicator_1 = c(5L, 12L, 8L,
7L, 6L), indicator_2 = c(13L, 10L, 6L, 5L, 8L), indicator_3 = c(9L,
7L, 4L, 8L, 12L)), class = "data.frame", row.names = c(NA,
-5L))
df_indicators <- structure(list(Ind = c("indicator_1",
"indicator_2", "indicator_3"
), weights = 2:4), class = "data.frame", row.names = c(NA, -3L
))https://stackoverflow.com/questions/68085495
复制相似问题