基于多列计算VC基金的统计指标:总估值、总投资次数
计算VC基金的统计指标
原始数据
R语言代码生成的数据:
df <- data.frame(Company = c("X", "Y","Z"), Valuation = c("10","20","30"), VC.1 = c("Zeev Ventures","Bedrock Capital","Activant Capital"), VC.2 = c("Bedrock Capital","Activant Capital","Zeev Ventures"))
对应的数据表:
| Company | Valuation | VC.1 | VC.2 |
|---|---|---|---|
| X | 10 | Zeev Ventures | Bedrock Capital |
| Y | 20 | Bedrock Capital | Activant Capital |
| Z | 30 | Activant Capital | Zeev Ventures |
目标结果
需要按VC基金分组,计算总估值和投资次数,得到如下统计结果:
| VC | Total Valuation | Total Investments |
|---|---|---|
| Zeev Ventures | 40 | 2 |
| Bedrock Capital | 40 | 2 |
| Activant Capital | 50 | 2 |
解决方案
方法1:使用tidyverse工具包
适合熟悉tidy语法的用户,步骤清晰易读:
# 加载工具包 library(tidyverse) # 先将Valuation转为数值型(原始数据是字符格式) df$Valuation <- as.numeric(df$Valuation) # 将宽格式的VC列转换为长格式 df_long <- df %>% pivot_longer(cols = starts_with("VC."), # 选择所有以VC.开头的列 names_to = "VC_Column", # 原列名存到VC_Column(后续会丢弃) values_to = "VC") %>% # 提取的VC名称存到VC列 select(-VC_Column) # 移除多余的列 # 分组计算统计指标 vc_stats <- df_long %>% group_by(VC) %>% summarise( Total_Valuation = sum(Valuation), # 计算总估值 Total_Investments = n() # 统计投资次数 ) %>% ungroup() # 输出结果 vc_stats
方法2:使用Base R
无需额外安装包,适合偏好原生R语法的用户:
# 转换Valuation为数值型 df$Valuation <- as.numeric(df$Valuation) # 提取所有VC名称和对应的估值 vc_names <- c(df$VC.1, df$VC.2) valuation_values <- rep(df$Valuation, 2) # 每个公司的估值对应两个VC,重复两次 # 创建长格式数据框 vc_df <- data.frame(VC = vc_names, Valuation = valuation_values) # 分组聚合计算 vc_stats_base <- aggregate( Valuation ~ VC, data = vc_df, FUN = function(x) c( Total_Valuation = sum(x), Total_Investments = length(x) ) ) # 展开聚合结果为标准数据框 vc_stats_base <- do.call(data.frame, vc_stats_base) names(vc_stats_base) <- c("VC", "Total_Valuation", "Total_Investments") # 输出结果 vc_stats_base
两种方法最终都会得到你需要的统计结果。
内容的提问来源于stack exchange,提问作者Igor Glushkov
相关产品推荐
相关产品推荐

