Using janitor::tabyl() I get a desired contingency table output. This is done to check whether certain combinations are present, that should NOT be present. Therefore, I would like to create an extra column called "number_of_errors" that counts the combinations (by row), that I input.
If I run a tabyl on the iris dataset, for instance:
gapminder %>%
tabyl(year, continent)
output:
year Africa Americas Asia Europe Oceania
1952 52 25 33 30 2
1957 52 25 33 30 2
1962 52 25 33 30 2
1967 52 25 33 30 2
1972 52 25 33 30 2
1977 52 25 33 30 2
1982 52 25 33 30 2
1987 52 25 33 30 2
1992 52 25 33 30 2
1997 52 25 33 30 2
2002 52 25 33 30 2
2007 52 25 33 30 2
And now I would like to create an extra column, that counted certain combinations, that I give it. For instance, let's say that the combination 1952 and Europe can not exists, nor can 1962 have the value Oceania NOR Asia. Therefore, I want to create a column called "number_of_errors" with this desired output:
year Africa Americas Asia Europe Oceania number_of_erros
1952 52 25 33 30 2 30
1957 52 25 33 30 2 0
1962 52 25 33 30 2 35
1967 52 25 33 30 2 0
1972 52 25 33 30 2 0
1977 52 25 33 30 2 0
1982 52 25 33 30 2 0
1987 52 25 33 30 2 0
1992 52 25 33 30 2 0
1997 52 25 33 30 2 0
2002 52 25 33 30 2 0
2007 52 25 33 30 2 0
I have tried with a mutate and case_when, but to no avail. I've got this far:
out <- gapminder %>%
tabyl(year, continent)
out %>%
mutate(number_of_errors = case_when(subset(out, year == "1952") == "Europe") ~ count(subset(out, year == "1952") == "Europe")),
subset(out, year == "1962) == "Asia" | subset(out, year == "1962") == "Oceania") ~ sum(count(subset(out, year == "1962) == "Asia", count(subset(out, year == "1962) == "Oceania"))
Not sure if this made sense. There must be something more elegant and easy that works
Thanks