I want to count pairs across several columns. That is, with more than two columns, count the number of times particular value pairs occur in the same row.
Say I asked some people whether they liked different kinds of food, and they could answer "yes" or "no". I ended up with this data set:
foods <-
data.frame(
fruit = c("yes", "yes", "no"),
veg = c("yes", "yes", "yes"),
meat = c("yes", "no", "yes")
)
foods
I'd like to count the number of times any two foods received a "yes". I hope to end up with something like this:
desired <-
data.frame(
pair.1 = c("fruit", "fruit", "veg"),
pair.2 = c("veg", "meat", "meat"),
Freq = c(2, 1, 2)
)
desired
This could also work:
desired.2 <-
data.frame(
pair. = c("fruit, veg", "fruit, meat", "veg, meat"),
Freq = c(2, 1, 2)
)
desired.2
If possible, I hope I could use a solution to eventually do the same for combinations of 3, 4, and so on (my actual data has more than 3 columns). What's a good solution to this, preferably using dplyr?
Thank you in advance for your help!