Combining with mutate()
- the replace_na
function
Let’s look at the yearly CO2 emissions dataset we loaded earlier.
replace_na({data frame}, {list of values})
or replace_na({vector}, {single value})
yearly_co2 %>%
select(country, starts_with("194")) %>%
mutate(across(
c(`1943`, `1944`, `1945`),
function(x) replace_na(x, replace = 0)
))
# A tibble: 192 × 11
country `1940` `1941` `1942` `1943` `1944` `1945` `1946` `1947` `1948`
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Afghanistan NA NA NA 0 0 0 NA NA NA
2 Albania 693 627 744 462 154 121 484 928 704
3 Algeria 238 312 499 469 499 616 763 744 803
4 Andorra NA NA NA 0 0 0 NA NA NA
5 Angola NA NA NA 0 0 0 NA NA NA
6 Antigua and B… NA NA NA 0 0 0 NA NA NA
7 Argentina 15900 14000 13500 14100 14000 13700 13700 14500 17400
8 Armenia 848 745 513 655 613 649 730 878 935
9 Australia 29100 34600 36500 35000 34200 32700 35500 38000 38500
10 Austria 7350 7980 8560 9620 9400 4570 12800 17600 24500
# ℹ 182 more rows
# ℹ 1 more variable: `1949` <dbl>