如何为分组样本数据创建符合条件的税率变量
Got it, let's work through this together. Your panel dataset has country-year observations, and we need to create a tax rate variable that hits all three of your requirements. Since you're already using data.table, we'll lean into its fast grouping capabilities to make this clean and efficient.
Step 1: Prep the Data (and Stick with Data.Table)
First, let's convert your data back to a data.table (it's far more efficient for grouping operations):
DT <- as.data.table(DT)
Step 2: Assign a Base Tax Rate to Each Country
To ensure the same country's yearly rates never differ by more than 5%, we'll start with a base rate for each country. We'll set this base between 10% and 35%—this way, even if we adjust up or down by 5%, we'll never go outside your 10%-40% range.
# Get unique countries in your dataset unique_countries <- unique(DT$country) # Generate base tax rates (10-35%, with 0.1% precision) set.seed(123) # Keep results reproducible country_base_tax <- data.table( country = unique_countries, base_tax = sample(seq(10, 35, by = 0.1), length(unique_countries), replace = TRUE) )
Step 3: Generate Yearly Tax Rates for Each Country-Year Group
Now we'll merge the base rates into your dataset, then generate a unique tax rate for each country-year pair—ensuring it's within ±5% of the country's base rate, and all observations in the same country-year get the same rate.
# Merge base rates into the main dataset DT <- DT[country_base_tax, on = "country"] # Generate tax rates per country-year group set.seed(123) DT[, tax_rate := sample(seq( max(10, base_tax - 5), # Ensure we don't go below 10% min(40, base_tax + 5), # Ensure we don't go above 40% by = 0.1 ), 1), by = .(country, year)] # Clean up: remove the base_tax column if you don't need it DT[, base_tax := NULL]
Verify Your Conditions
Let's double-check that all requirements are met:
- Same rate per country-year: Run
DT[, .N, by = .(country, year, tax_rate)]—each group'sNshould match the number of observations for that country-year. - Rates between 10-40%: Run
range(DT$tax_rate)—you'll see it's bounded correctly. - Yearly difference ≤5% per country: Run
DT[, diff(range(tax_rate)), by = country]—all values will be ≤5.
Tweaks if Needed
- If you want integer tax rates, change
by = 0.1toby = 1in theseq()calls. - Adjust the precision (e.g.,
by = 0.01for two decimal places) if you need more granular rates.
内容的提问来源于stack exchange,提问作者Tom

