首页 > 解决方案 > 合并相同的日期

问题描述

我有这种格式的数据

data.frame(id = c(1,1,2), 
           date = c("2008-08-04 05:45:07","2008-08-04 09:45:07","2008-08-04 05:45:07"), 
           text = c("stg","another","final"))
#   id                date    text
# 1  1 2008-08-04 05:45:07     stg
# 2  1 2008-08-04 09:45:07 another
# 3  2 2008-08-04 05:45:07   final

如何将具有相同日期的行合并为具有相同 ID 的行。预期输出示例:

data.frame(id = c(1,2), 
           date = c("2008-08-04", "2008-08-04"), 
           text = c("stg another","final"))
#   id       date        text
# 1  1 2008-08-04 stg another
# 2  2 2008-08-04       final

标签: r

解决方案


您可以尝试aggregate如下

dfout <- aggregate(text ~ date + id, df, paste)

这样

> dfout
  id                date       text
1  1 2008-08-04 05:45:07 stg, final
2  2 2008-08-04 09:45:07    another

推荐阅读