Sum of unique values in column.

Hi everyone.

Let's say, I have a column 'Model' and 3 values: Basic, Premium and Lux. How to sum distinct each type of model? I want to group by Model.
I believe I have to use group by, summarise and n_distinct functions, right? but how to use them properly I do not know.

Here are a couple ways to accomplish a distinct sum of each type of model.

Using the approach you described...

d = data.frame(model =c(rep('Basic', 7), rep('Premium', 4), rep('Lux', 11)))

d |>
  group_by(model) |>
  summarise(n = n()) |>


You could also use the count() function to achieve the same result.

count(d, model)
1 Like

@scottyd22 thank you for your quick response :pray: :pray: :pray:
i used this code and it worked perfectly

hotel_bookings %>%
group_by(distribution_channel) %>%

Excllent! One thing to note in your example is that when you use count(), you don't even need the group_by() line, thus making it even more succinct.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.