DSR-004Research DSCODE

R dplyr:sample proportion of the data frame、left join 两个 data frame;simulation:给定一个 data frame,随机选一半保持原价、另一半涨价 10%,算每个模拟数据集的平均价

📋 题目详细背景与场景

4)编程:主要涉及的都是R 的dplyr的应用 包括sample proportion of the data frame (slice_sample()),left join two data frames,还有一些simulation study。比如given one data frame, randomly select half of them being the same price, the rest being increased 10% in price, compute the average of price for each simulated data

💡 官方参考解答与考察要点

考官评估核心: 用 R dplyr(slice_sample 与 left_join)及 Python pandas 对等实现表抽样、连接与价格扰动 Monte Carlo simulation,重点防范多对多 join 膨胀与样本随机种子复现。
  • 问题建模与假设:抽样需明确无放回比例抽样(prop = 0.5)与随机种子固定;left_join 需确认右表关联键唯一性,防止多对多匹配导致行数从 N 膨胀(参考关联键唯一性排查)。
  • 核心实现与复杂度:抽样与分组均值汇总通过哈希连接与列式向量化完成,单次模拟时间复杂度 O(N),B 次 Monte Carlo 模拟复杂度 O(B * N);在大表模拟时用索引数组采样(无需全表物理复制)可降空间至 O(N)。
  • 生产边界与权衡:当数据存在奇数行时,精确取 floor(N/2) 还是按独立 Bernoulli(0.5) 抽取一半会在小样本下产生细微方差差异;left_join 必须校验未匹配导致的 NA/NaN 对后续价格均值计算的影响。
  • 常见追问(大规模模拟优化):若需跑 10,000 次价格敏感性模拟,可将价格向量提取到 NumPy/R matrix 批量生成 0/1 掩码矩阵做矩阵乘法,比在 DataFrame 循环中反复 join/mutate 快百倍。
# R (dplyr): sample_df <- slice_sample(df, prop = 0.5)
# joined <- left_join(df_a, df_b, by = 'id', relationship = 'many-to-one')

import numpy as np
import pandas as pd

def simulate_price_shock(df: pd.DataFrame, n_sims: int = 1000, seed: int = 42) -> np.ndarray:
    if df.empty or 'price' not in df.columns:
        return np.array([], dtype=float)
    rng = np.random.default_rng(seed)
    prices = df['price'].to_numpy(dtype=float)
    n = len(prices)
    half = n // 2
    sim_means = np.empty(n_sims, dtype=float)
    for i in range(n_sims):
        # 随机选一半保持原价,其余涨价 10%
        keep_idx = rng.choice(n, size=half, replace=False)
        mult = np.full(n, 1.10, dtype=float)
        mult[keep_idx] = 1.0
        sim_means[i] = np.mean(prices * mult)
    return sim_means

📖 对应核心知识点手册:

想用苏格拉底式对话深入理解该考点的第一性原理?

进入破冰推演实验室,模拟考官互动并一步步拆解底层机制与直觉陷阱。

💬 针对本考点破冰 ➔
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔