Let's say I have a sample data set, p1, where different users have rated 4 different types of food, like so:
Food_ID Rating
1 Good
1 Good
2 Good
2 Bad
1 Bad
3 Bad
3 Good
4 Bad
1 Bad
4 Good
4 Good
4 Good
2 Bad
3 Bad
How can I write a code that tells me the acceptance rating of Food_ID based on the Good vs Bad ratings?
SELECT
Food_ID,
sum(Rating)/count(Rating) AS Avg_Rating
FROM p1
GROUP BY Food_ID
Obviously this code won't work because rating is a character column...is there a quick way to convert it to Boolean? Then perhaps it might? Or is there a simpler way altogether?
Thanks!
EDIT UPDATE:
Thanks to answers below, I've made progress. The following code:
sqldf("
SELECT food_id,
sum(CASE WHEN rating = 'Good' THEN 1 ELSE 0 END) AS good_reviews,
count(*) AS all_reviews,
sum(CASE WHEN rating = 'Good' THEN 1 ELSE 0 END) / count(*) AS acceptance
FROM p1
GROUP BY food_id
")
Which returns the following output:
food_id good_reviews all_reviews acceptance
1 2 4 0
2 1 3 0
3 0 3 0
4 3 4 0