Lets say that I have a data.frame with fruits and prices.
df <- data.frame(
fruit = c("bananas", "melons", "bananas", "melons", "apples", "bananas",
"apples", "melons", "lemons", "melons", "bananas", "apples",
"oranges", "apples", "apples", "lemons", "melons", "apples"),
prize = c(1,1,3,2,3,2,1,3,1,2,2,1,3,2,2,1,2,1)
)
For every unique value in the categorical "fruits" column, I want to count the number of times it is equal to each unique value of my other column "prize".
I have tried to do i as follows:
smry_bananas <- df %>%
filter(fruit == 'bananas') %>%
group_by(prize) %>%
summarise(n_1 = sum(prize == '1'),
n_2 = sum(prize == '2'),
n_3 = sum(prize == '3')) %>%
mutate(freq_1 = n_1/sum(n_1 + n_2 + n_3)) %>%
mutate(freq_2 = n_2/sum(n_1 + n_2 + n_3)) %>%
mutate(freq_3 = n_3/sum(n_1 + n_2 + n_3))
This works, but I would like to iterate over the unique values of the "fruits" column and not have to write all these lines for each unique value of the column.
I suppose I should use a for loop ir lapply, but I'm not that experienced with these. Thanks in advance, it is much appreciated