[英]How to combine row with some condition?
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. 我的条件是,如果数据具有相同的ID和相同的AccessTime小时,则ReferrerCode将被合并。 What should I do to make it happen? 我应该怎么做才能做到这一点?
Here's a base
R solution with aggregate()
, and sub()
to extract the hour from AccessTime
. 这是一个base
R解决方案,带有aggregate()
和sub()
来从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: 如果要在ReferrerCode
中将结果作为character
获取,请使用以下命令:
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. 我假设AccessTime
是POSIXlt
格式。 From character
you can convert by 从character
可以转换为
data$AccessTime <- as.POSIXlt(data$AccessTime, format="%H:%M:%S")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.