添加一个包含每天行数的列

Add a column with numbers of rows per day

我只是想在我的数据框中添加一列 (NbRowsPerDays),其中包含每天的行数。我的 df 是千行长度。

这意味着:

device_id   UTC_date     UTC_time   datatype NbRowsPerDays
   182207   2018-08-31   05:40:59      GPS        2
   182207   2018-08-31   05:42:00      GPS        2
   182207   2018-09-01   05:44:00      GPS        1
   182207   2018-10-02   05:46:00      GPS        5
   182207   2018-10-02   05:48:00      GPS        5
   182207   2018-10-02   05:49:59      GPS        5
   182207   2018-10-02   05:40:59      GPS        5
   182207   2018-10-02   05:42:00      GPS        5
   182207   2018-11-06   05:44:00      GPS        2
   182207   2018-11-06   05:46:00      GPS        2
   182207   2018-12-15   05:48:00      GPS        1
   182207   2018-12-26   05:49:59      GPS        1

UTC_date 是一个因素。 我知道如何找到每天的行数,但我不知道如何将这些值放在一个新列中,多行具有相同的值。希望有人能帮助我。谢谢 !

您可以使用 ave 添加一个包含每天行数的列 使用函数 length 并按 UTC_date 分组:

x$NbRowsPerDays <- ave(seq_len(nrow(x)), x$UTC_date, FUN=length)
x
#   device_id   UTC_date UTC_time datatype NbRowsPerDays
#1     182207 2018-08-31 05:40:59      GPS             2
#2     182207 2018-08-31 05:42:00      GPS             2
#3     182207 2018-09-01 05:44:00      GPS             1
#4     182207 2018-10-02 05:46:00      GPS             5
#5     182207 2018-10-02 05:48:00      GPS             5
#6     182207 2018-10-02 05:49:59      GPS             5
#7     182207 2018-10-02 05:40:59      GPS             5
#8     182207 2018-10-02 05:42:00      GPS             5
#9     182207 2018-11-06 05:44:00      GPS             2
#10    182207 2018-11-06 05:46:00      GPS             2
#11    182207 2018-12-15 05:48:00      GPS             1
#12    182207 2018-12-26 05:49:59      GPS             1

数据:

x <- read.table(header=TRUE, text="device_id   UTC_date     UTC_time   datatype NbRowsPerDays
   182207   2018-08-31   05:40:59      GPS        2
   182207   2018-08-31   05:42:00      GPS        2
   182207   2018-09-01   05:44:00      GPS        1
   182207   2018-10-02   05:46:00      GPS        5
   182207   2018-10-02   05:48:00      GPS        5
   182207   2018-10-02   05:49:59      GPS        5
   182207   2018-10-02   05:40:59      GPS        5
   182207   2018-10-02   05:42:00      GPS        5
   182207   2018-11-06   05:44:00      GPS        2
   182207   2018-11-06   05:46:00      GPS        2
   182207   2018-12-15   05:48:00      GPS        1
   182207   2018-12-26   05:49:59      GPS        1")