我只想在我的dataframe中添加一个列(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是一个因素。我知道如何为每天找到行数,但我不知道如何将这些值放在一个新列中,其中几行的值相同。希望有人能帮我。谢谢!
发布于 2020-04-27 09:26:06
您可以使用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")
https://stackoverflow.com/questions/61455356
复制相似问题