【问题标题】:R: How to Count Rows with Subsetted Date in Date Formatted ColumnR:如何在日期格式列中计算具有子集日期的行
【发布时间】:2019-10-30 07:56:45
【问题描述】:

我有大约 30,000 行数据,其中包含日期格式的日期列。我希望能够按月/年和年计算行数,但是当我使用下面的代码聚合时,我会在数据表中得到一个向量来表示我的结果,而不是一个数字。

使用超链接的csv文件,我试过聚合函数。

https://www.dropbox.com/s/a26t1gvbqaznjy0/myfiles.csv?dl=0

short.date <- strftime(myfiles$Date, "%Y/%m")
aggr.stat <- aggregate(myfiles$Date ~ short.date, FUN = count)

下面是 aggr.stat 数据框的视图。有两列,以“c(”开头的第二列是我想查看计数值的列。

1 1969/01 c(-365, -358, -351, -347, -346)

2 1969/02 c(-323, -320)

3 1969/03 c(-306, -292, -290)

4 1969/04 c(-275, -272, -271, -269, -261, -255)

5 1969/05 c(-245, -240, -231)

6 1969/06 c(-214, -211, -210, -205, -204, -201, -200, -194, -190, -186)

【问题讨论】:

标签: r count aggregate


【解决方案1】:

我不太喜欢从互联网上下载任何未知文件,因此您必须根据您的需要调整我提出的解决方案。

您可以借助 data.table 和 lubridate 解决问题。

假设您的数据至少有一列名为 dates 的实际日期(也就是说,调用 class(df$dates) 将至少返回 Date 或类似的东西(POSIXct 等)。

# load libraries
library(data.table)
library(lubridate)

# convert df to a data.table
setDT(df)

# count rows per month
df[, .N, by = .(monthDate = floor_date(dates, "month")]

.N 计算行数,by = 对数据进行分组。有关详细信息,请参阅?data.table

【讨论】:

    【解决方案2】:

    考虑从数据帧运行所有内容。具体来说,将所需的月/年列添加到数据框中,然后使用 data 参数运行aggregate(而不是通过单独的向量运行)。最后,base R 中没有count() 函数,改用length

    # NEW COLUMN
    myfiles$short.date <- strftime(myfiles$Date, "%Y/%m")
    
    # AGGREGATE WITH SPECIFIED DATA
    aggr.stat <- aggregate(Date ~ short.date, data = myfiles, FUN = length)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      相关资源
      最近更新 更多