如何在R中按年份计算唯一值?
我有这样一个数据集:如何在R中按年份计算唯一值?,r,grouping,unique,R,Grouping,Unique,我有这样一个数据集: Year Month Day Location Target Perpetrator 1970 5 1 Place1 x A 1970 7 5 Place2 y A 1971 2 3 Place3 x B 1972 10 8 Place4 x C 1972 12 13 Place2 y C 1973 1 3 Place5 z
Year Month Day Location Target Perpetrator
1970 5 1 Place1 x A
1970 7 5 Place2 y A
1971 2 3 Place3 x B
1972 10 8 Place4 x C
1972 12 13 Place2 y C
1973 1 3 Place5 z B
我完全不知道该怎么做。我试过了
data <- data %>%
distinct() %>%
count(Perpetrator)
数据%
不同的()%>%
罪名(犯罪人)
当然,这只给了我“罪犯”中每个独特价值的计数
我得到的输出是每年“罪犯”中每个唯一值的计数。我如何才能做到这一点?在base R中,我们可以使用
tapply
with(dat, tapply(Perpetrator, Year, FUN=length))
# 1970 1971 1972 1973
# 2 1 2 1
数据:
dat在base R中,我们可以使用tapply
with(dat, tapply(Perpetrator, Year, FUN=length))
# 1970 1971 1972 1973
# 2 1 2 1
数据:
dat trydata%%>%groupby(Year)%%>%distinct()%%>%count(罪犯)
这正是我要找的!我已经试了好几个小时了,多亏了这么多,其他方法(不会导致TIBLE)是从plyr
包中的ddply(数据,.(年份),摘要,n=n_distinct(罪犯))
。我个人喜欢这种方式,因为我讨厌tibbles:这能回答你的问题吗?您可以count
多变量data%>%count(年份,犯罪者)
尝试data%>%groupby(年份)%%>%distinct()%%>%count(犯罪者)
这正是我要找的!我已经试了好几个小时了,多亏了这么多,其他方法(不会导致TIBLE)是从plyr
包中的ddply(数据,.(年份),摘要,n=n_distinct(罪犯))
。我个人喜欢这种方式,因为我讨厌tibbles:这能回答你的问题吗?您可以count
多变量data%>%count(年份,犯罪人)