I have dataset like this,
> data
ID AccessTime ReferrerCode
101 01:17:40 910
103 01:27:53 135
103 01:33:12 222
202 02:04:11 921
202 03:40:30 106
103 03:45:02 734
And I want to transform my dataset like this,
> data
ID ReferrerCode
101 910
103 135 222
202 921
202 106
103 734
My condition is ReferrerCode will be combined if the data has the same ID and the same hour of AccessTime. What should I do to make it happen?
Here's a base
R solution with aggregate()
, and sub()
to extract the hour from AccessTime
.
aggregate(ReferrerCode ~ ID + sub(':.*$', '', AccessTime), c, data=data)[,-2]
# ID ReferrerCode
#1 101 910
#2 103 135, 222
#3 202 921
#4 103 734
#5 202 106
If you want to get the result as character
in ReferrerCode
use this:
aggregate(ReferrerCode ~ ID + hour(AccessTime), data, FUN=function(x) paste(x, collapse=" "))[,c(1,3)]
ID ReferrerCode
1 101 910
2 103 135 222
3 202 921
4 103 734
5 202 106
I assumed that AccessTime
is in POSIXlt
format. From character
you can convert by
data$AccessTime <- as.POSIXlt(data$AccessTime, format="%H:%M:%S")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.