eliran azulay
eliran azulay

Reputation: 119

aggregate and count unique values in R

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

Upvotes: 0

Views: 134

Answers (1)

akrun
akrun

Reputation: 887981

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))

Upvotes: 1

Related Questions