I have a dataframe with time data, with which I'd like to mark certain rows as belonging to a period of interest. For example:
time <- c(1,2,3,5,7,9,23,24,28,43,45)
action <- c("clap","blink","stare","stare","clap","stare",
"clap","blink","stare","clap","stare")
I'd like to find what happens within, say, 5 second of each clap, hopefully by creating a new column which would have an index marker for each new sequence of clap and post-clap.
I'm quite a novice with R so there might be a way of phrasing this that would help with searching for an answer, so my apologies if that is the case.
I believe this does what you want. Note that I have added a row to your data.frame
, since you mention you want an identifier to see if something happens within 5 seconds from a clap.
# Your data
time <- c(1,2,3,5,7,9,23,24,28,43,45)
action <- c("clap","blink","stare","stare","clap","stare",
"clap","blink","stare","clap","stare")
df = data.frame(time=time,action=action)
# Added a row that does not occur within 5 seconds of a clap for illustration purposes.
df = rbind(df,data.frame(time=100,action='stare'))
# Add the group number, based on the claps.
df = df %>% mutate(group=cumsum(action=='clap'))
# Check if action is within 5 seconds of a clap.
df = df %>%
group_by(group) %>%
mutate(within_5_seconds = ifelse(time-time[1]<=5,1,0)) %>%
as.data.table
Output:
time action group within_5_seconds
1: 1 clap 1 1
2: 2 blink 1 1
3: 3 stare 1 1
4: 5 stare 1 1
5: 7 clap 2 1
6: 9 stare 2 1
7: 23 clap 3 1
8: 24 blink 3 1
9: 28 stare 3 1
10: 43 clap 4 1
11: 45 stare 4 1
12: 100 stare 4 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.