2016-02-13 43 views
1

我试图计算一个取决于多个其他列的值的变量,但是在其他行中。 这里的样本数据:确定组内是否有最近发生的事件

set.seed(2) 
df1 <- data.frame(Participant=c(rep(1,5),rep(2,7),rep(3,10)), 

          Action=sample(c(rep("Play",9),rep("Other",13))), 
          time = c(sort(runif(5,1,100)),sort(runif(7,1,100)),sort(runif(10,1,100)))) 
df1$Action[2] ="Play" # edited to provide important test case 

我想实现的是测试的最后一个“玩”事件是否是至多10秒前(时间列)的列。如果在过去10秒内没有“播放”事件,StillPlaying的值应为“n”,而不管当前操作如何。下面是我想什么,有一个样本:

Part Action time  StillPlaying 
1 1 Play 15.77544 n 
2 1 Play 15.89964 y 
3 1 Other 35.37995 n 
4 1 Play 49.38855 n 
5 1 Other 83.85203 n 
6 2 Other 2.031038 n 
7 2 Play 14.10483 n 
8 2 Other 17.29958 y 
9 2 Play 36.3492  n 
10 2 Play 81.20902 n 
11 2 Other 87.01724 y 
12 2 Other 96.30176 n 
+0

http://stackoverflow.com/questions/3558988/basic-lag-in-r-vector-dataframe –

+0

应该播放/其他操作分开考虑? – jalapic

回答

2

好像要组由参与者和国旗行动“其他”,并在最后一个“玩”是在10秒内的任何行。为此,您可以在dplyr使用group_by,使用cummax来确定最后一次出现“播放”行动:

library(dplyr) 
df1 %>% 
    group_by(Participant) %>% 
    mutate(StillPlaying=ifelse(time - c(-100, head(cummax(ifelse(Action == "Play", time, -100)), -1)) <= 10, "y", "n")) 
# Participant Action  time StillPlaying 
#   (dbl) (fctr)  (dbl)  (chr) 
# 1   1 Play 15.775439   n 
# 2   1 Play 15.899643   y 
# 3   1 Other 35.379953   n 
# 4   1 Play 49.388550   n 
# 5   1 Other 83.852029   n 
# 6   2 Other 2.031038   n 
# 7   2 Play 14.104828   n 
# 8   2 Other 17.299582   y 
# 9   2 Play 36.349196   n 
# 10   2 Play 81.209022   n 
# ..   ... ...  ...   ... 

如果你想记住这基础R,你可以做分申请,结合与使用相同的基本命令:

do.call(rbind, lapply(split(df1, df1$Participant), function(x) { 
    x$StillPlaying <- ifelse(x$time - c(-100, head(cummax(ifelse(x$Action == "Play", x$time, -100)), -1)) <= 10, "y", "n") 
    x 
})) 
#  Participant Action  time StillPlaying 
# 1.1   1 Play 15.775439   n 
# 1.2   1 Play 15.899643   y 
# 1.3   1 Other 35.379953   n 
# 1.4   1 Play 49.388550   n 
# 1.5   1 Other 83.852029   n 
# 2.6   2 Other 2.031038   n 
# 2.7   2 Play 14.104828   n 
# 2.8   2 Other 17.299582   y 
# 2.9   2 Play 36.349196   n 
# 2.10   2 Play 81.209022   n 
# 2.11   2 Other 87.017243   y 
# 2.12   2 Other 96.301761   n 
# ... 
+0

对不起,我测试了更多的解决方案,并意识到我的问题不是很清楚 - 我想知道在每一个行动,是否还在玩(所以要么玩或其他行动)。我设法修改代码以完成我所需要的工作:_ ** df1%>% group_by(参与者)%>% mutate(StillPlaying = ifelse(time - cummax(ifelse(Action ==“Play”,time ,-100))<= 10, “y”,“n”))_ ** 但我希望公式在播放动作时表示“n”,当没有别的东西在播放时。感谢任何指针。 – Esther

+0

@Esther我已根据您对该问题的修改更新了答案 – josliber

相关问题