Reputation: 3
I want conditional sum in R. I have dataframe with 6 column.
I want sum breeding count about equal condition(same [year, month, kind, gender, type]) and age <= 20 and changed row's age is 20.
My hope : age = 3,4,5, ...., 20 --> age = 20 (18 row to 1 row) group by other column and sum breeding count. So data(have age = 20)'s breeding count column contain age=3~20 breeding count
year month kind gender age breeding_count type
<chr> <dbl> <chr> <chr> <dbl> <dbl> <chr>
1 2022 12 한우 암 3 65043 breeding
2 2022 12 한우 암 4 31740 breeding
3 2022 12 한우 암 5 36680 breeding
4 2022 12 한우 암 6 42295 breeding
5 2022 12 한우 암 7 49243 breeding
6 2022 12 한우 암 8 58414 breeding
'''
I expect all age<= 20 to age == 20 group by year, month, kind, gender, type Like this,
A tibble: 22 × 8
year month kind gender age breeding_count slaughter_count rate
<chr> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 2014 1 젖소 젖소 20 7249 9 0.124
2 2014 1 젖소 젖소 21 5416 5 0.0922
3 2014 1 젖소 젖소 22 5498 5 0.0909
4 2014 1 젖소 젖소 23 7431 9 0.121
5 2014 1 젖소 젖소 24 6979 20 0.286
6 2014 1 젖소 젖소 25 7372 25 0.338
7 2014 1 젖소 젖소 26 7457 22 0.294
8 2014 1 젖소 젖소 27 4823 18 0.372
9 2014 1 젖소 젖소 28 4471 23 0.512
10 2014 1 젖소 젖소 29 6312 22 0.347
Upvotes: 0
Views: 51
Reputation: 15123
You may try
library(dplyr)
df
year month kind gender age breeding_count type
1 2022 12 한우 암 3 65043 breeding
2 2022 12 한우 암 4 31740 breeding
3 2022 12 한우 암 5 36680 breeding
4 2022 12 한우 암 6 42295 breeding
5 2022 12 한우 암 7 49243 breeding
6 2022 12 한우 암 8 58414 breeding
df %>%
mutate(age = ifelse(age <= 20, 20, age)) %>%
group_by(year, month, kind, gender, age, type) %>%
summarise(breeding_count = sum(breeding_count))
year month kind gender age type breeding_count
<int> <int> <chr> <chr> <dbl> <chr> <int>
1 2022 12 한우 암 20 breeding 283415
Upvotes: 1