hi, i have already done a lot of searching and tinkering, but i can't seem to figure out my problem.
i have a dataframe that looks like this:
# A tibble: 14,293 x 7
# Groups: year [10]
year prov_id saidin facility_type beds treat `__index_level_0__`
<chr> <chr> <dbl> <chr> <dbl> <dbl> <int>
1 2001 11z111 0.537 govt 35 0 0
2 2001 11z113 0.195 govt 40 0 1
3 2001 11z132 0.474 govt 211 0 2
4 2001 11z135 0.817 nonprof 55 0 3
5 2001 11z13z 0.195 govt 34 0 4
6 2001 11z142 0.537 nonprof 195 0 5
7 2001 11z161 2.23 nonprof 487 0 6
8 2001 11z163 0.195 NA 174 0 7
9 2001 11z165 1.38 nonprof 336 0 8
10 2001 11z177 0.537 NA 255 0 9
# … with 14,283 more rows
i am trying to subtract the 2004 value of saidin
for each provider in each year.
for example, if i were to do this for provider_1
, this would mean that i want to subtract the 2004 value of saidin
for provider_1
for years 2001 through 2010. the 2004 value would be 0 after this is done. i seek to do this for all providers.
i've tried different implementations of the code below, but i keep getting this error. what should i do? thanks in advance for any advice.
tech_data_long6 %>%
group_by(prov_id, year) %>%
mutate(saidin_standardized = saidin - saidin[year == '2004'])
Error: Problem with `mutate()` input `saidin_standardized`.
x Input `saidin_standardized` can't be recycled to size 1.
ℹ Input `saidin_standardized` is `saidin - saidin[year == "2004"]`.
ℹ Input `saidin_standardized` must be size 1, not 0.
ℹ The error occurred in group 1: prov_id = "11z111", year = "2001".
Run `rlang::last_error()` to see where the error occurred.
edit: i apologize for not including a reproducible example. i hope the code i've pasted below will suffice. please let me know if not.
test_dat <- data.frame(year = rep(2001:2004, 3),
prov_id = rep(c('a', 'b', 'c', 'd'), 3),
saidin = runif(12, 0, 1))
test_dat %>%
group_by(prov_id, year) %>%
mutate(saidin_standardized = saidin - saidin[year == 2004])
Error: Problem with `mutate()` input `saidin_standardized`.
x Input `saidin_standardized` can't be recycled to size 3.
ℹ Input `saidin_standardized` is `saidin - saidin[year == 2004]`.
ℹ Input `saidin_standardized` must be size 3 or 1, not 0.
ℹ The error occurred in group 1: prov_id = "a", year = 2001.
Run `rlang::last_error()` to see where the error occurred.