【问题标题】:Collapse and aggregate several row values by date按日期折叠和聚合多个行值
【发布时间】:2016-06-30 16:35:35
【问题描述】:

我有一个如下所示的数据集:

date, location, value, tally, score
2016-06-30T09:30Z, home, foo, 1,
2016-06-30T12:30Z, work, foo, 2,
2016-06-30T19:30Z, home, bar, , 5

我需要将这些行聚合在一起,以获得如下结果:

date, location, value, tally, score
2016-06-30, [home, work], [foor, bar], 3, 5

对我来说有几个挑战:

  • 生成的行(每日汇总)必须包含当天的行(在我上面的示例中为 2016 年 6 月 30 日)
  • 某些行(字符串)将生成一个包含当天所有值的数组
  • 其他一些(整数)将产生总和

我查看了dplyr,如果可能的话,我想在 R 中执行此操作。

感谢您的帮助!


编辑:

这是dput 的数据

structure(list(date = structure(1:3, .Label = c("2016-06-30T09:30Z", 
"2016-06-30T12:30Z", "2016-06-30T19:30Z"), class = "factor"), 
    location = structure(c(1L, 2L, 1L), .Label = c("home", "work"
    ), class = "factor"), value = structure(c(2L, 2L, 1L), .Label = c("bar", 
    "foo"), class = "factor"), tally = c(1L, 2L, NA), score = c(NA, 
    NA, 5L)), .Names = c("date", "location", "value", "tally", 
"score"), class = "data.frame", row.names = c(NA, -3L))

【问题讨论】:

  • @Hack-R:哎呀对不起!我用 dput 修改了我的问题。

标签: r


【解决方案1】:
mydat<-structure(list(date = structure(1:3, .Label = c("2016-06-30T09:30Z", 
                                                       "2016-06-30T12:30Z", "2016-06-30T19:30Z"), class = "factor"), 
                      location = structure(c(1L, 2L, 1L), .Label = c("home", "work"
                      ), class = "factor"), value = structure(c(2L, 2L, 1L), .Label = c("bar", 
                                                                                        "foo"), class = "factor"), tally = c(1L, 2L, NA), score = c(NA, 
                                                                                                                                                    NA, 5L)), .Names = c("date", "location", "value", "tally", 
                                                                                                                                                                         "score"), class = "data.frame", row.names = c(NA, -3L))

mydat$date <- as.Date(mydat$date)

require(data.table)
mydat.dt <- data.table(mydat)
mydat.dt <- mydat.dt[, lapply(.SD, paste0, collapse=" "), by = date]

cbind(mydat.dt, aggregate(mydat[,c("tally", "score")], by=list(mydat$date), FUN = sum, na.rm=T)[2:3])

给你:

         date       location       value tally score
1: 2016-06-30 home work home foo foo bar     3     5

请注意,如果您愿意,您可能可以在重塑 data.table 的过程中一步完成所有操作,但我发现这是一种更快、更简单的方法,我只需两步即可完成相同的任务。

【讨论】:

猜你喜欢
  • 2021-10-16
  • 2020-11-26
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多