将活动开始和结束时间转换为R dplyr / tidyr中多个组的分箱数据

问题描述 投票:2回答:1

我的数据看起来像这样:

foo <- data.frame(userid = c("a","a","b","b","b"),
                  activity = factor(c("x","y","z","z","x")),
                  st=c(0, 20,   0, 10, 25), # start time
                  et=c(20, 30, 10, 25, 30)) # end time

我希望,对于每个用户标识,将活动数据转换为五分钟的时间段。结果看起来像这样:

result <- data.frame(userid = c("a", "b"),
                         x1 = c("x", "z"),
                         x2 = c("x", "z"),
                         x3 = c("x", "z"),
                         x4 = c("x", "z"),
                         x5 = c("y", "z"),
                         x6 = c("y", "x"))

以下方法有效,但它非常麻烦且非常慢。这在我适度大小的数据集上大约需要15分钟。

library(dplyr)
library(tidyr)

lvls <- levels(foo$activity)

time_bin <- function(st, et, act) {
  bins <- seq(0, 30, by=5)
  tb <- as.integer(bins>=st & bins<et)*as.integer(act)
  tb[tb>0] <- lvls[tb]
  data.frame(tb=tb, bins=bins)
}

new_foo <- 
  foo %>% 
  rowwise() %>%
  do(data.frame(., time_bin(.$st, .$et, .$activity))) %>%
  select(-(activity:et)) %>%
  group_by(userid) %>%
  subset(tb>0) %>%
  spread(bins, tb)

有没有更快或更方便的方式来解决这个问题?

r performance dplyr binning
1个回答
3
投票

你可以试试:

library(data.table)
library(reshape2)

dt = setDT(foo)[,seq(min(st)+5,max(et),5),.(userid,activity)]
dcast(dt, userid~V1, value.var='activity')
#  userid 5 10 15 20 25 30
#1      a x  x  x  x  y  y
#2      b z  z  z  z  z  x
© www.soinside.com 2019 - 2024. All rights reserved.