JimmyJim JimmyJim - 1 year ago 108
R Question

Merge rows which have the same date within a data frame

I have a data.frame as follows:

timestamp index negative positive sentiment
<dttm> <dbl> <dbl> <dbl> <dbl>
1 2015-10-29 15:00:10 0 11 10 -1
2 2015-10-29 17:26:48 0 1 5 4
3 2015-10-29 17:30:07 0 10 22 12
4 2015-10-29 20:13:22 0 5 6 1
5 2015-10-30 14:25:26 0 3 2 -1
6 2015-10-30 18:22:30 0 14 15 1
7 2015-10-31 14:16:00 0 10 23 13
8 2015-11-02 20:30:18 0 14 7 -7
9 2015-11-03 14:15:00 0 8 26 18
10 2015-11-03 16:52:30 0 12 34 22


I would like to know if there is a possibility to merge rows with equal days such that i have a scoring for each day, since I have absolutely no clue how to approach this problem because I dont even know how to unlist each date and write a function which merges only equal dates, because the time differs in each day . I would like to obtain a data.frame which has the following form:

timestamp index negative positive sentiment
<dttm> <dbl> <dbl> <dbl> <dbl>
1 2015-10-29 0 27 43 16
2 2015-10-30 0 3 2 -1
3 2015-10-31 0 17 17 0
4 2015-11-02 0 14 7 -7
5 2015-11-03 0 20 60 40


Is there any possibility to get around to this result? I would be thankful for any hint.

Answer Source

You can use aggregate() to do this. Before doing that, you'll need to show that it should sort according to the day, ignoring the exact time-point.

I will assume you have your data stored as df:

aggregate(df[ ,2:5], FUN="sum", by=list(as.Date(df$timestamp, "%Y-%m-%d")))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download