I want to group a data frame by a column (owner) and output a new data frame that has counts of each type of a factor at each observation. The real data frame is fairly larg
In 2017 the answer is
library(dplyr)
library(tidyr)
gather(df, key, value, -owner) %>%
group_by(owner, key, value) %>%
tally %>%
spread(value, n, fill = 0)
Which gives output
Source: local data frame [4 x 4]
Groups: owner, key [4]
owner key loud quiet
*
1 0 obs1 1 1
2 0 obs2 2 0
3 1 obs1 1 1
4 1 obs2 0 2
In 2019 the answer is:
gather(df, key, value, -owner) %>%
count(owner, key, value) %>%
spread(value, n, fill = 0)