Let\'s say I have the following data frame:
> myvec name order_no 1 Amy 12 2 Jack 14 3 Jack 16 4 Dave 11 5 Amy
A data.table approach
data.table
library(data.table) DT <- data.table(myvec) DT[, .(number_of_distinct_orders = length(unique(order_no))), by = name]
data.table v >= 1.9.5 has a built in uniqueN function now
uniqueN
DT[, .(number_of_distinct_orders = uniqueN(order_no)), by = name]