0

I have a data set of Vehicle types as factors (11,12,13=type of cars) for each Vehicle type I have a number of Unit Id (=specific cars) I want to count how many uniqe UnitId I have in each vehicle Type. i tried: aggregate(UnitId~VehicleType, test, unique)->res1

Carl
  • 4,232
  • 2
  • 12
  • 24
eliran azulay
  • 119
  • 1
  • 1
  • 6
  • 2
    Try `aggregate(UnitId~VehicleType, test, function(x) length(unique(x)))` or use `with(test, table(UnitId, VehicleType))` – akrun Jan 17 '15 at 10:32
  • 2
    using `table`, it should be `with(test, colSums(!!table(UnitId, VehicleType)))` – akrun Jan 17 '15 at 10:41
  • 1
    Or with dplyr: `library(dplyr); test %>% distinct(VehicleType, UnitID) %>% count(VehicleType)` – talat Jan 17 '15 at 11:07
  • Please add a reproducible example for your problem. See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – nico Jan 17 '15 at 11:24
  • your code works! thx! is there a way to find out if a UnitId appers in more then one VehicleType? – eliran azulay Jan 17 '15 at 11:42

1 Answers1

1

For the updated question, i.e. "is there a way to find out if a UnitId appers in more then one VehicleType"

 with(test, names(rowSums(!!table(UnitId, VehicleType))>1))

Copy/pasting from the comments based on your original question ("counting unique values by group")

aggregate(UnitId~VehicleType, test, function(x) length(unique(x)))

Or

with(test, colSums(!!table(UnitId, VehicleType)))

Or

library(data.table)
setDT(test)[, length(unique(UnitId)), VehicleType]

data

set.seed(24)
test <- data.frame(VehicleType=sample(11:18,60, replace=TRUE), 
  UnitId=sample(1:10, 60, replace=TRUE))
akrun
  • 874,273
  • 37
  • 540
  • 662