R中按日期计算唯一值的数量 [英] Counting the number of unique values by date in R

查看:33
本文介绍了R中按日期计算唯一值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我计算每个日期的唯一 ID 数.所以,最初,有这个 ID 和日期的数据框

Please help me to count the number of unique IDs per Date. so, initially, there is this data frame of IDs and dates

 ID         Date 
 1        2009/11/1
 1        2009/11/2
 1        2009/11/2
 2        2009/11/1
 2        2009/11/1
 2        2009/11/2 
 3        2009/11/1
 3        2009/11/3  

可以按日期重新排列.如果我们这样做,那么我们将看到在 1 日有 3 个唯一 ID.在第 2 个唯一 ID 和第 3 个唯一 ID 上.所以决赛桌应该是这样的:

It is possible to rearrange it by date. If we do so then we will see that on the 1st there are 3 unique IDs. On the 2ed 2 unique ID and on the 3rd there is one unique ID. So the final table should look like this:

  Date      uniqueIDs
2009/11/1      3
2009/11/2      2
2009/11/3      1

我知道,如果值为1"或0",则可以使用 sumaggregate 进行聚合:

I know that it is possible to aggregate with aggregate by using sum if the value is '1' or '0 'like that:

aggregate(DataFrame$RoomAv ~ DataFrame$Date, DataFrame, sum)

但是如何计算每天唯一的 ID 数量?ID 列是整数列.

But how to count the unique number of IDs per day? The ID column is an integer column.

非常感谢!

推荐答案

这是 sqldf 的解决方案.

library(sqldf)

rawData <-"ID,Date 
 1,2009/11/1
 1,2009/11/2
 1,2009/11/2
 2,2009/11/1
 2,2009/11/1
 2,2009/11/2 
 3,2009/11/1
 3,2009/11/3 "

data <- read.csv(text = rawData,as.is=TRUE)

sqlStmt <- "select Date, count(distinct ID) from data group by Date"
sqldf(sqlStmt)

...和输出:

> sqldf(sqlStmt)
       Date count(distinct ID)
1 2009/11/1                  3
2 2009/11/2                  2
3 2009/11/3                  1
>

这篇关于R中按日期计算唯一值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆