You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:基于多条件计算数据框中银行资产权重

R语言实现分组计算银行总资产权重

需求说明:基于**国家(Country)、年份(year)、银行类型(Specialization)**三个维度分组,为每家银行计算总资产权重,公式为:
w(i) = 该银行总资产 / 同组所有银行总资产之和

示例数据

banks <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
Country <- c("NL", "ES", "IT", "IT", "ES", "NL", "FR", "NL", "ES", "NL", "IT", "IT", "NL", "ES", "NL")
year <- c(2020, 2019, 2018, 2019, 2020, 2020, 2018, 2019, 2019, 2019, 2018, 2019, 2020, 2018, 2020)
Specialization <- c("cooperative", "saving", "cooperative", "cooperative", "saving", "cooperative", "saving", "cooperative", "cooperative", "saving", "cooperative", "saving", "cooperative", "cooperative", "cooperative")
Tot_Assets <- c(100, 200, 145, 300, 200, 345, 543, 190, 150, 120, 310, 210, 110, 210, 220)
data <- data.frame(banks, Country, year, Specialization, Tot_Assets)

解决方案

方法一:使用dplyr包(简洁直观)

dplyr的分组操作可以快速实现需求:

# 安装并加载dplyr(首次使用需执行安装)
# install.packages("dplyr")
library(dplyr)

# 计算权重并添加到数据框,保留两位小数匹配示例格式
data_with_weight <- data %>%
  group_by(Country, year, Specialization) %>%
  mutate(weight = round(Tot_Assets / sum(Tot_Assets), 2)) %>%
  ungroup()

# 查看结果
print(data_with_weight)

方法二:使用Base R实现(无需额外包)

利用ave()函数实现分组求和,再计算权重:

# 计算分组内总资产总和
group_total <- ave(data$Tot_Assets, 
                   list(data$Country, data$year, data$Specialization), 
                   FUN = sum)

# 添加权重列,保留两位小数
data$weight <- round(data$Tot_Assets / group_total, 2)

# 查看结果
print(data)

结果验证

以银行1为例,其所属分组为NL、2020、cooperative,同组银行还有6、13、15,总资产总和为100+345+110+220=775,计算得权重100/775≈0.13,与示例一致。

内容的提问来源于stack exchange,提问作者Martina Noli Maio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:48:21