What is the best way to expand out a contingency table (Case C, below) or a data frame with a count variable (Case B) into the taller data frame where each row is one of those cases that is aggregated into the count (Case A)? It seems to me you can go from C to B via functions in tidyr, but I'm wondering if there is a cleaner way to go from B to A than dipping into rep() and all that. Perhaps a group_by() %>% disaggregate() or an untally()?
While this operation seems like a bad idea from an efficiency standpoint, I can think of two use cases: transforming the data frame in preparation for subsequent visualization or modeling functions that expect that format, and in situations where you want to join with additional individual-level variables.
library(tidyverse)
# Case A: tidy data where the case is a single plant
CO2 %>%
select(Plant:Treatment) %>%
glimpse()
# Observations: 84
# Variables: 3
# $ Plant <ord> Qn1, Qn1, Qn1, Qn1, Qn1, Qn1, Qn1, Qn2, Qn2, Q...
# $ Type <fctr> Quebec, Quebec, Quebec, Quebec, Quebec, Quebe...
# $ Treatment <fctr> nonchilled, nonchilled, nonchilled, nonchille...
# Case B: tidy data where the case is the plantXtypeXtreatment combo
CO2 %>%
group_by(Plant, Type, Treatment) %>%
summarize(count = n())
# Source: local data frame [12 x 4]
# Groups: Plant, Type [?]
#
# Plant Type Treatment count
# <ord> <fctr> <fctr> <int>
# 1 Qn1 Quebec nonchilled 7
# 2 Qn2 Quebec nonchilled 7
# 3 Qn3 Quebec nonchilled 7
# 4 Qc1 Quebec chilled 7
# 5 Qc3 Quebec chilled 7
# Case C: non-tidy contingency table
CO2 %>%
select(Type, Treatment) %>%
table()
# Treatment
# Type nonchilled chilled
# Quebec 21 21
# Mississippi 21 21
@ismayc
What is the best way to expand out a contingency table (Case C, below) or a data frame with a count variable (Case B) into the taller data frame where each row is one of those cases that is aggregated into the count (Case A)? It seems to me you can go from C to B via functions in
tidyr, but I'm wondering if there is a cleaner way to go from B to A than dipping intorep()and all that. Perhaps agroup_by() %>% disaggregate()or anuntally()?While this operation seems like a bad idea from an efficiency standpoint, I can think of two use cases: transforming the data frame in preparation for subsequent visualization or modeling functions that expect that format, and in situations where you want to join with additional individual-level variables.
@ismayc