[英]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.我有一个车辆类型的数据集作为每种车辆类型的因素(11,12,13=汽车类型)我有许多单位 ID(=特定汽车)我想计算每辆车有多少个唯一的单位 ID类型。 i tried: aggregate(UnitId~VehicleType, test, unique)->res1
我试过: aggregate(UnitId~VehicleType, test, unique)->res1
For the updated question, ie "is there a way to find out if a UnitId appers in more then one VehicleType"对于更新后的问题,即“有没有办法找出 UnitId 是否出现在多个 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]
set.seed(24)
test <- data.frame(VehicleType=sample(11:18,60, replace=TRUE),
UnitId=sample(1:10, 60, replace=TRUE))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.