def add_deviations_from_sample_mean(data):
    """
    Adds columns in which [profitability, inv_rate] are demeaned at the firm-level and then the full-sample mean is added again.

    Args
    ----
    data (pandas.DataFrame):           dataframe with 4 columns: firm, year, profitability, inv_rate

    Returns
    -------
    data_merges (pandas.DataFrame):    dataframe with additional columns profitability_adj, inv_adj
    """
    mean_by_firm = data.groupby(by=["%firm_id"]).mean()

    data_merged = data.merge(mean_by_firm, how="left", on="%firm_id", suffixes=("", "_firmmean"))

    variables = ["profitability", "inv_rate"]
    for var in variables:
        data_merged[var + "_adj"] = data_merged[var] - data_merged[var + "_firmmean"] # + data_merged[var].mean()

    data_merged.drop(list(data_merged.filter(regex = '_firmmean')), axis=1, inplace=True)

    return data_merged