Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

Find the time of next instance in R

I got the first three columns and would like to find the fourth col (NextOrderTime), meaning that the next Orderfood == "Y" of each client.

DF:

Client    Time      Orderfood?  NextOrderTime 
 A   2021/1/7 12:00    N       2021/1/7 12:02 
 A   2021/1/7 12:01    N       2021/1/7 12:02 
 A   2021/1/7 12:02    Y       2021/1/7 12:06 
 B   2021/1/7 12:03    N       2021/1/7 12:08 
 B   2021/1/7 12:04    N       2021/1/7 12:08 
 B   2021/1/7 12:05    N       2021/1/7 12:08 
 A   2021/1/7 12:06    Y           NA 
 B   2021/1/7 12:07    N       2021/1/7 12:08 
 B   2021/1/7 12:08    Y           NA

Any help would be appreciated. Thanks for the time!

question from:https://stackoverflow.com/questions/65895107/find-the-time-of-next-instance-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a way using dplyr :

We get the next Orderfood == 'Y' row number for each Client and get the corresponding Time from it.

library(dplyr)

df %>%
  group_by(Client) %>%
  mutate(NextOrderTime = replace(row_number(), Orderfood == 'N', NA),  
         NextOrderTime = lead(NextOrderTime)) %>%
  tidyr::fill(NextOrderTime, .direction = 'up') %>%
  mutate(NextOrderTime = Time[NextOrderTime])

#  Client Time           Orderfood NextOrderTime 
#  <chr>  <chr>          <chr>     <chr>         
#1 A      2021/1/7 12:00 N         2021/1/7 12:02
#2 A      2021/1/7 12:01 N         2021/1/7 12:02
#3 A      2021/1/7 12:02 Y         2021/1/7 12:06
#4 B      2021/1/7 12:03 N         2021/1/7 12:08
#5 B      2021/1/7 12:04 N         2021/1/7 12:08
#6 B      2021/1/7 12:05 N         2021/1/7 12:08
#7 A      2021/1/7 12:06 Y         NA            
#8 B      2021/1/7 12:07 N         2021/1/7 12:08
#9 B      2021/1/7 12:08 Y         NA            

data

df <- structure(list(Client = c("A", "A", "A", "B", "B", "B", "A", 
"B", "B"), Time = c("2021/1/7 12:00", "2021/1/7 12:01", "2021/1/7 12:02", 
"2021/1/7 12:03", "2021/1/7 12:04", "2021/1/7 12:05", "2021/1/7 12:06", 
"2021/1/7 12:07", "2021/1/7 12:08"), Orderfood = c("N", "N", 
"Y", "N", "N", "N", "Y", "N", "Y")), row.names = c(NA, -9L),class = "data.frame")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...