I currently have a data frame with one factor and multiple logical variables (that correspond to some extent to various conditions of a single variable, but are NOT excluding one another).
Taking a simplistic comparison, I want to count cars from different types of people, but someone can have various cars. And let's say I also want to count their phone type (also not excluding one another).
data = data.frame(Profession = c("Manager", "Manager", "Developer", "Developer"), Ford = c(T, F, F, T), Renault = c(F, T, T, F), Ferrari = c(T, F, F, F), iPhone = c(T, T, T, F), Android = c(T, T, F, T))
# Profession Ford Renault Ferrari iPhone Android
# 1 Manager TRUE FALSE TRUE TRUE TRUE
# 2 Manager FALSE TRUE FALSE TRUE TRUE
# 3 Developer FALSE TRUE FALSE TRUE FALSE
# 4 Developer TRUE FALSE FALSE FALSE TRUE
Manager Developer (Total)
- Ford 1 1 2
- Renault 1 1 2
- Ferrari 1 0 1
- iPhone 2 1 3
- Android 2 1 3
This should work:
# split the data by profession, result is a list with a dataframe for every profession data2 = split(data[, -1], data$Profession) # colSums is then equal to the frequencies per Ford, Renault, etc. # that is binded into a dataframe for convenience tb = data.frame(lapply(data2, colSums)) # add a column for total tb$Total = rowSums(tb)