我只是想在我的数据框中添加一列(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")